A.Pissicat A.Pissicat - 1 month ago 4
C# Question

What synchronism can I use?

I'm working in C# and i'm searching for a mechanism to synchronize my application.

I have a function to manage anomaly in my Application, working on multi-thread. When an anomaly is raised, a function is called, making some treatment and asking for user to check.

If a new anomaly is raised while the first is in progress I want to wait for the first and doing nothing after (function has been executed for the first)

How can I do that properly ?

My draft :

private void onAnomaly(enumAnomaly err)
{
if (anomalyInProgress)
//wait
return;
else
anomalyInProgess = true;
//do something
anomalyInProgess = false;
}

Answer

You can use Interlocked.Exchange method.

Edit according to your comments, you need the other functions to wait. You can do this by adding a lock object.

private int anomalyInProgress = 0;
private Object _lock = new Object();

private void onAnomaly(enumAnomaly err)
{
    //Here, the value of anomalyInProgress will be set to 1, but
    // Exchange return the value before the change.
    // So if it was 0 before, it means nobody is already executing this code
    //and we can safely enters
    if (0 == Interlocked.Exchange(anomalyInProgress, 1))
    {
        lock (_lock)
        {
            //do something

            //we reset the value of anomalyInProgress so the next one can enter in safely
            Interlocked.Exchange(anomalyInProgress, 0)
        }
    } 
    else 
    {
        //I cannot take the lock directly, because I could be taking it before the 'True' condition.
        Threading.Thread.Sleep(1)
        lock (_lock) //This will wait for the 'True' condition to finish
        {
        }
    }
}
Comments