One of the benefits of using multithreading in .NET is to improve the performance of our applications. We execute long running tasks in the background threads and make the UI thread idle to get the user's inputs.
We share resources between multiple threads such as memory. If multiple threads will try to update the data at the same time, the memory get corrupted and may give unpredictable data. To achieve the coordination between multiple threads, we use synchronization techniques in .NET threading.
In synchronization, we define a code region in which only one particular thread can enter at a time. When a thread exits, second thread get chance to enter it. Synchronization maintains the data integrity.
Critical Region refers to a code region which should be executed by only one thread.
.NET framework provides multiple synchronization primitives to achieve the synchronization between multiple threads.
Below are the list of Primitives:
- Concurrent Collections (ConcurrentQueue, ConcurrentStack, ConcurrentDictionary, ConcurrentBag)
In the next sections, I'll explained all synchronization primitives.