In this code snippet, we will take a look at thread synchronization with Monitor and Lock in C#.
In this post, I showed how to start new threads to execute code in parallel. However, when you start using threads what can happen is that two threads will access the same resources at the same time. One thread might modify a variable before another thread is done executing. This can, of course, cause errors.
To prevent this from happening we have to lock the resources in question and prevent other threads from using them until the current thread is done executing. We can do this by either using the Monitor class or the lock keyword. These two approaches are functionally identical. The only difference (as you will be able to see in the code below) is that lock is more compact and easier to use.
You will notice that we have to provide Monitor.Start/Monitor.End and lock an object to lock on. The object being locked is just some “random” object we create to lock on(more specifically it’s synchronization block). Any properties of that object can actually still be accessed by another thread while the object is locked. The code between Monitor.Enter and Monitor.Exit or inside the lock code block is the actual code that is locked and is not allowed to be modified by another thread. Kind of silly and confusing isn’t it? But that is how it works.
Let’s have a look at the code below to see how to lock resources.