17.5 C
Canberra
Sunday, February 23, 2025

Find out 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 means that you can 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 technique on an occasion of the Mutex class to lock a useful resource and the ReleaseMutex technique 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 knowledge to a textual content file.


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

        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 technique as a parameter is written to a textual content file. The lastly block then releases the mutex by making a name to the ReleaseMutex technique.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles