Showing posts with label Difference between lock and Monitor.Enter(). Show all posts
Showing posts with label Difference between lock and Monitor.Enter(). Show all posts

Tuesday 17 January 2012

Difference between lock and Monitor.Enter()

Difference between lock and Monitor.Enter()


lock keyword basically provides a shortcut to Enter method of Monitor class.
Monitor is used to provide thread synchronization.It means till the Thread in which the method is being used finishes its task, no other thread can access the object.

example:

lock (object)
{

}

It is compiled into

Monitor.Enter(object);
try
{
//code
}
finally
{
Monitor.Exit(object);
}

See the MSIL of the assembly.

We can write much more code and perform customization in the try block.