The objective of this segment is to understand the concept of thread synchronization in C# programming language. Let's try to understand the concept with simple situation. When we start threads within a program, there may be a situation when multiple threads accessing the same resources and create a concurrency problem. For example, suppose one thread writing data to a text file, so at the same time, another thread can’t write data to the same file. If we try so, it will create a concurrency issue. Hence, the concept of synchronization comes into the picture. With the help of synchronization, we can synchronize access to a shared resource or coordinate thread interaction.
The synchronization in C# achieved using the lock keyword. The lock controls access to block of code with an object. When an object locked by one thread block, then no other threads can access the locked block (no context-switching between the threads happen). Once the lock released by one thread, then only other threads can access it.
kodingwindow@kw:~/csharp$ dotnet run 100 101 102 103 104 105 100 101 102 103 104 105 kodingwindow@kw:~/csharp$