Purpose of object in argument of Lock statement

Viewed 743

What is the purpose of object in Lock argument. Here is an example:

public class TestThreading  
{  
    private System.Object lockThis = new System.Object();  

    public void Process()  
    {  

        lock (lockThis)  
        {  
            // Access thread-sensitive resources.  
        }  
    }  

} 

... does this 'lockThis' object pass anything into the Lock body. Why can't I use Lock statement without object in argument.

1 Answers

The object passed to the lock statement can be thought of as an identifier for the lock. For any object, only a single thread can obtain an exclusive lock on that object at any given time. By allowing an object to be passed to the lock statement, you can use different objects for different areas of critical code.

The Monitor.Enter documentation provides a better description of the use of the object than does the lock statement documentation.

Related