C# Threads And Resource Locking
In this tutorial, 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.









