"issue with manualresetevent not releasing all waiting threads consistently" Code Answer

37

Looks like your threads are not getting released from the ResetEvent before it is reset.

You could solve the problem by creating the event open and having the fist thread to enter your method reset it.

Alternatively you can avoid the vagaries of ManualResetEvent's behavior by doing something like this:

private object _latch = new object();
private bool _updating;

private void UpdateIfRequired() 
{
    lock (_latch) 
    {
        if (_updating) 
        {
            //wait here and short circuit out when the work is done
            while (_updating)
                Monitor.Wait(_latch);

            return;
        }

        _updating = true;
    }

    //do lots of expensive work here

    lock (_latch)
    {
        _updating = false;
        Monitor.PulseAll(_latch); //let the other threads go
    }
}

Check out this page for a great explanation as to how this works http://www.albahari.com/threading/part4.aspx#_Signaling_with_Wait_and_Pulse

By Eric Reyna on May 28 2022

Answers related to “issue with manualresetevent not releasing all waiting threads consistently”

Only authorized users can answer the Search term. Please sign in first, or register a free account.