Introduction to C# Thread Synchronization

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.

C# program to achieve thread synchronization using the lock keyword
Program.cs
ParallelThread pt = new ParallelThread();
Thread t1 = new Thread(new ThreadStart(pt.thread));
Thread t2 = new Thread(new ThreadStart(pt.thread));

t1.Start();
t2.Start();

class ParallelThread
{
    public void thread()
    {
        lock (this)
        {
            for (int i = 100; i <= 105; i++)
            {
                Console.Write(i + " ");
                Thread.Sleep(1500);
            }
        }
    }
}
Explanation:
In this program, we have used the lock keyword to execute a block of code synchronously. The output clearly shows that the two threads worked independently (one after another). When the first thread locked the block of code, then the object of the second thread can’t access the same block of code until it gets released from the first thread.
Output
kodingwindow@kw:~/csharp$ dotnet run
100 101 102 103 104 105 100 101 102 103 104 105
kodingwindow@kw:~/csharp$ 
What Next?
C# Reflection
Advertisement