C# Thread Synchronization
To allow only one thread to access the resource for a specified time, the technique of synchronization is used in C#. Until the specified task is completed by the assigned thread, no other thread can interrupt. Threads in a multithreading program can access any resource for the desired execution time, thus sharing the resources and executing the code asynchronously which sometimes may halt the system because accessing the shared resources or data is a critical task. Thus the thread synchronization is required here, especially for transactions like deposit, withdraw, etc.
Advantages of C# Thread Synchronization:
- Consistency Maintain
- No Thread Interference
C# Lock:
To execute a piece of C# code synchronously, the lock keyword is used. It locks the current thread which is released only after the execution of the task. Until the completion of the task, no thread can interrupt the execution.
Example: Without Synchronization
using System; using System.Threading; class Example { public void xyz() { for (char i = 'a'; i <= 'g'; i++) { Thread.Sleep(100); Console.WriteLine(i); } } } class uvw { public static void Main(string[] args) { Example ex = new Example(); Thread x = new Thread(new ThreadStart(ex.xyz)); Thread y = new Thread(new ThreadStart(ex.xyz)); x.Start(); y.Start(); } } |
Output:
Explanation:
In the above example, the lock keyword is not used to execute the code asynchronously. Here between the threads, there is context-switching.
Example: C# Thread Synchronization:
using System; using System.Threading; class Example { public void xyz() { lock (this) { for (char i = 'a'; i <= 'g'; i++) { Thread.Sleep(100); Console.WriteLine(i); } } } } class uvw { public static void Main(string[] args) { Example ex = new Example(); Thread x = new Thread(new ThreadStart(ex.xyz)); Thread y = new Thread(new ThreadStart(ex.xyz)); x.Start(); y.Start(); } } |
Output:
Explanation:
In the above example, the C# lock keyword is used to execute the code synchronously. Thus, between the threads, there is no context-switching. Here, as soon as the first thread completes its tasks, the second thread starts working.