Difference between lock and Monitor.Enter()

 Posted by Ddd on 3/15/2011 | Category: .NET Framework Interview questions | Views: 4636 | Points: 40
Answer:

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.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response