7.3 C
New York
Thursday, February 13, 2025

Learn how to use mutexes and semaphores in C#



A semaphore is used to restrict the variety of threads which have entry to a shared useful resource on the identical time. In different phrases, a Semaphore lets you implement non-exclusive locking and therefore restrict concurrency. You may consider a Semaphore as a non-exclusive type of a Mutex. In .NET, we use the System.Threading.Semaphore class to work with semaphores.

Create a mutex in C#

Let’s create a mutex object in .NET. Be aware that we use the WaitOne methodology on an occasion of the Mutex class to lock a useful resource and the ReleaseMutex methodology to unlock it.


Mutex mutexObject = new Mutex(false, "Demo");

attempt
{
    if (!mutexObject.WaitOne(TimeSpan.FromSeconds(10), false))
    {
        Console.WriteLine("Quitting for now as one other occasion is in execution...");
        return;
    }
}
lastly
{
    mutexObject.ReleaseMutex();
}

Allow us to now implement a real-life code instance that makes use of a mutex to synchronize entry to a shared useful resource. The next code itemizing demonstrates how you need to use a Mutex object in C# to synchronize entry to a essential part that writes information to a textual content file.


public static class FileLogger
{
    non-public const string fileName = @"D:ProjectsMyLog.txt";
    public static void WriteLog(string textual content)
    {
        utilizing var mutex = new Mutex(initiallyOwned: false, "Worldlog");

        attempt
        {
            mutex.WaitOne(1000);
            File.AppendAllText(fileName, textual content);
        }
        catch (AbandonedMutexException)
        {
            mutex.ReleaseMutex();
            mutex.WaitOne(1000);
            File.AppendAllText(fileName, textual content);
        }
        lastly
        {
            mutex.ReleaseMutex();
        }
    }
}

Within the FileLogger class proven above, an try is made to amass a mutex by blocking the present thread for 1000 milliseconds. If the mutex is acquired, the textual content handed to the AppendAllText methodology as a parameter is written to a textual content file. The lastly block then releases the mutex by making a name to the ReleaseMutex methodology.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles