Synchronization is a technology that allows only one thread to access certain resources at a specific time. No other thread can interrupt until the assigned thread or the currently accessed thread completes its task.
In a multithreaded program, the execution time required for threads to access any resource. Threads share resources and execute asynchronously. Accessing shared resources (data) is a critical task that can sometimes pause the system. So it can be processed through thread synchronization.
Main scenarios such as: deposits, withdrawals and other transactions.
Advantages of thread synchronization
- Consistency maintenance
- Wireless interfering
C# lock
Using C#lock
Keywords synchronous execution of the program. It is used to lock the current thread, perform tasks, and then release the lock. It ensures that other threads do not interrupt execution before execution is completed.
Below, create two examples of asynchronous and synchronous.
C# Example: Asynchronous
In this example, we do not use locks. This example executes asynchronously. In other words, there is context switching between threads.
using System; using ; class Printer { public void PrintTable() { for (int i = 1; i <= 5; i++) { Thread t = ; (200); (+" "+i); } } } class Program { public static void Main(string[] args) { Printer p = new Printer(); Thread t1 = new Thread(new ThreadStart()); Thread t2 = new Thread(new ThreadStart()); = "Thread 1 :"; = "Thread 2 :"; (); (); } }
Execute the above sample code and you can see the following output results -
Thread 2 : 1
Thread 1 : 1
Thread 2 : 2
Thread 1 : 2
Thread 2 : 3
Thread 1 : 3
Thread 2 : 4
Thread 1 : 4
Thread 2 : 5
Thread 1 : 5
C# thread synchronization example
In this example, we uselock
block, so the example executes synchronously. In other words, there is no context switching between threads. In the output section, you can see that the second thread starts executing after the first thread completes the task.
using System; using ; class Printer { public void PrintTable() { lock (this) { for (int i = 1; i <= 5; i++) { Thread t = ; (100); ( + " " + i); } } } } class Program { public static void Main(string[] args) { Printer p = new Printer(); Thread t1 = new Thread(new ThreadStart()); Thread t2 = new Thread(new ThreadStart()); = "Thread 1 :"; = "Thread 2 :"; (); (); } }
Execute the above sample code and you can see the following output results -
Thread 1 : 1
Thread 1 : 2
Thread 1 : 3
Thread 1 : 4
Thread 1 : 5
Thread 2 : 1
Thread 2 : 2
Thread 2 : 3
Thread 2 : 4
Thread 2 : 5
The above is a brief analysis of the detailed content of c# thread synchronization. For more information about c# thread synchronization, please pay attention to my other related articles!