Threads and Thread Synchronization in C#


Using Synchronization, you can synchronize access to resources in multithreaded applications.

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.

Thread pool in C# is a collection of threads. It is used to perform tasks in the background. When a thread completes a task, it is sent to the queue wherein all the waiting threads are present. This is done so that it can be reused.

Let us see how to create a thread pool.

Firstly, use the following namespace −

using System.Threading;

Now, call the threadpool class, using the threadpool object. Call the method QueueUserWorkItem.

ThreadPool.QueueUserWorkItem(new WaitCallback(Run));

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();

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements