In this post, I will try to briefly explain how locking mechanisms provided by .NET work and how CLR manages to keep track of locks and do the synchronization, allowing us to achieve mutual exclusion. TL;DR: Every reference type instance has some extra fields in memory, one of which can be used to store (or at least point to) the information that can indicate whether some thread has acquired a lock on that object. CLR looks that up before allowing the thread to acquire a lock on the object. Consider the following code class Foo { private static readonly object _lock = new object(); public void DoSomething() { lock(_lock) { //Do some work on shared resources } } } which is the same as class Foo { private static readonly object _lock = new object(); public void DoSomething() { Monitor.Enter(_lock); try { // Do some work on shared resources } finally { Monitor.Exit(_lock); } } } Only a single thread at a time can access the shared resources using a DoSomething method. If another thread tries to access the shared resources using DoSomething method, it will be blocked until first thread releases the lock.


I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too.

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.


This article is related to


c#