What is the Mutex and semaphore In c#? where we need to implement?

33,205

Solution 1

You should start at MSDN.

Generally you only use a Mutex across processes, e.g. if you have a resource that multiple applications must share, or if you want to build a single-instanced app (i.e. only allow 1 copy to be running at one time).

A semaphore allows you to limit access to a specific number of simultaneous threads, so that you could have, for example, a maximum of two threads executing a specific code path at a time.

Solution 2

I'd start by reading this: http://www.albahari.com/threading/part2.aspx#_Synchronization_Essentials and then bolster it with the MSDN links bobbymcr posted.

Solution 3

You might want to check out the lock statement. It can handle the vast majority of thread synchonization tasks in C#

class Test {
    private static object Lock = new object();

    public function Synchronized()
    {
        lock(Lock)
        {
            // Only one thread at a time is able to enter this section
        }
    }
}

The lock statement is implemented by calling Monitor.Enter and Monitor.Exit. It is equivalent to the following code:

Monitor.Enter(Lock);    
try
{
    // Only one thread at a time is able to enter this section
}
finally
{
    Monitor.Exit(Lock);
}
Share:
33,205
Jaswant Agarwal
Author by

Jaswant Agarwal

Enjoying coding from last few years

Updated on July 09, 2022

Comments

  • Jaswant Agarwal
    Jaswant Agarwal almost 2 years

    What is the Mutex and semaphore in C#? Where we need to implement?

    How can we work with them in multithreading?

  • Steve Gilham
    Steve Gilham over 14 years
    +1 for MSDN. It's the RTFM-goto for everything in the Windows API space.
  • Lazy
    Lazy over 14 years
    Nice answer, and potentially useful, but not really an answer to the posed question. Thought about a -1, but leaving it at this comment. ;-)
  • KadekM
    KadekM over 10 years
    Well the implementation is changed in C# 5.0 :)
  • Sam Rueby
    Sam Rueby over 6 years
    Semaphores can also be used to synchronize across processes."Named system semaphores are visible throughout the operating system, and can be used to synchronize the activities of processes": msdn.microsoft.com/en-us/library/…