Difference between lock(...) and Monitor.Enter

S

Shawn B.

Greetings,

What is the difference between lock(...) and Monitor.Enter(...) /
Monitor.Exit(...) ?


Thanks,
Shawn
 
R

Richard Blewett [DevelopMentor]

Consider this code:

lock(myGuard)
{
// do some stuff that is being synchronized
}

the C# compiler generates the following code for you

Monitor.Enter(myGuard);
try
{
// do some stuff that is being synchronized
}
finally
{
Monitor.Exit(myGuard);
}

So lock is an exception proof (and short) way of acquiring a monitor and making sure it gets freed again.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Greetings,

What is the difference between lock(...) and Monitor.Enter(...) /
Monitor.Exit(...) ?


Thanks,
Shawn
 
G

Guest

the keyword lock can replac ethe usage of Monitor.Enter

If i'm correct, there are no differences between this 2 methods.

Bye.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top