C# Monitor class in multithreading with examples

What Is Monitor Class In C#?

Monitor class: In C#, the Monitor class provides a wait based synchronization mechanism that allows only one thread to access a critical section of code at a time to avoid the race condition.
Here all the other threads have to wait and halt the execution until the locked object is released.

The  Monitor.Enter  method is used to acquire an exclusive lock on the object whereas  Monitor.Exit  method is used to release the locked object.

In order to use the Monitor class in a multithreading , we first need to import the  System.Threading  namespace.

C# Monitor class in multithreading

Continue reading “C# Monitor class in multithreading with examples”

Lock Statement In C# – When To Use Lock keyword

This post series we will go through the understanding of the lock statement, monitor, mutex, and semaphore available in C#.

All of these classes provide a synchronization mechanism to protect the shared code or resources in a multithreaded application.

Let’s first understand the lock statement in C#.

C# Lock Statement

Lock Statement: In C#, the  lock  is a synchronization mechanism that allows only one thread to access a specified piece of code or a common field at a time.

It is mainly used to achieve an exclusive lock to avoid inconsistent output while reading and writing to a common variable in a multithreaded environment.

Generally, the  lock  keyword is placed around a critical section of code, where we want to allow only one thread to access the resource at a time.
All the other threads have to wait and halt the execution until the locked object is released.

Pictorial representation of mutual exclusion of lock

Lock in C#

Continue reading “Lock Statement In C# – When To Use Lock keyword”

Multithreading in C#

What is Multithreading?

Multithreading in C# is a process to execute multiple threads simultaneously to run multiple programs or tasks at a time.

In C#, multithreading helps us to run multiple tasks parallelly or asynchronously.

In order to create a multithreading application, we need to import System.Threading namespace.

Let’s understand the concept of Synchronous and Asynchronous programming in C#.

Synchronous: In Synchronous programming, all the tasks run in a sequence. Here, the next task has to wait until the first task gets completed.

In simple words, synchronous means executing one or more tasks one after the other.

Pictorial representation of synchronous processing

threading in C#

Continue reading “Multithreading in C#”