Alex Rivera | Logout

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

Asked 2009-10-12T06:26:47.817
24

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

How can we work with them in multithreading?

Edit
Report

1 Answer

6

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);
}
answered 2009-10-12T07:10:29.257

Your Answer