Thread Synchronization in C#

CsharpProgrammingServer Side Programming

Synchronize access to resources in multithreaded applications using Synchronization.

Mutex to Synchronize Threads

A mutex can be used to synchronize threads across processes. Use it to prevent the simultaneous execution of a block of code by more than one thread at a time.

C# lock statement is used to ensure that a block of code runs without interruption by other threads. A Mutual-exclusion lock is obtained for a given object for the duration of the code block.

A lock statement gets an object as an argument. The parameter given to the “lock” should be an object based on a reference type −

public class Demo {
   private System.Object myLock = new System.Object();
   public void Process() {
      lock (myLock) {
      }
   }
}

The Mutex class in C# is a synchronization primitive that can also be used for interprocess synchronization.

Let us see how to create a new Mutex −

private static Mutex m = new Mutex();
raja
Published on 21-Aug-2018 16:14:30
Advertisements