Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# What's the correct way to implement Semaphore Slim in this context

I heared about semaphore slim to limit thread access to something but I dont know its exact usage in async context?

if (!LOGS_FILE.Equals(string.Empty) && File.Exists(LOGS_FILE))
{
    using (StreamWriter STREAM_WRITER = new StreamWriter(LOGS_FILE, true))
    {
        STREAM_WRITER.WriteLine(LOG);
    }
}

if (IsDebuggerAttached())
{
    System.Diagnostics.Debug.WriteLine(LOG);
}

ALL_LOGS += LOG + "\n";

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Try this:

try
{
    SEMAPHORE_SLIM.Wait();

    if (!LOGS_FILE.Equals(string.Empty) && File.Exists(LOGS_FILE))
    {
        using (StreamWriter STREAM_WRITER = new StreamWriter(LOGS_FILE, true))
        {
            STREAM_WRITER.WriteLine(LOG);
        }
    }

    if (IsDebuggerAttached())
    {
        System.Diagnostics.Debug.WriteLine(LOG);
    }

    ALL_LOGS += LOG + "\n";
}
finally
{
    SEMAPHORE_SLIM.Release();
}

EDIT: Added try finally block

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading