Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi Wait handle

I have code such as:

public void MethodA()
{
    MyManualResetEvent.Reset();
}

public void MethodB()
{
    MyManualResetEvent.Set();
}

This works when using MyManualResetEvent.WaitOne() to stop a thread if another thread has called MethodA but not MethodB.

What i want to do now is be able to call MethodA twice, with another thread only continuing if MethodB is called twice, rather than just once.

I'm hoping there's something in the System.Threading namespace i don't know about.

like image 215
George Duckett Avatar asked Jul 15 '26 04:07

George Duckett


2 Answers

CountdownEvent may be what you are looking for.

From MSDN: "Represents a synchronization primitive that is signaled when its count reaches zero." http://msdn.microsoft.com/en-us/library/system.threading.countdownevent.aspx It's only available in .NET 4.
like image 169
Klinger Avatar answered Jul 17 '26 21:07

Klinger


Assuming you don't need to stop a concurrently-executing BlockedMethod the instant MethodA is called, this is probably most easily solved with the standard Monitor class. MethodA and MethodB share a counter which records how many times MethodA has been called without a corresponding call to MethodB. The BlockedMethod method only proceeds if that count is 0; if not, it waits for MethodB to signal it that it's time to proceed.

object mylock = new object();
int count = 0;

public void MethodA()
{
    // record that MethodA is executing
    lock (mylock)
        count++;

    // other code...
}

public void MethodB()
{
    // other code...

    lock (mylock)
    {
        // MethodB has now finished running
        count--;

        // wake up other thread because it may now be allowed to run
        Monitor.Pulse(mylock);
    }
}

public void BlockedMethod()
{
    // wait until the number of calls to A and B is equal (i.e., count is 0)
    lock (mylock)
    {
        while (count != 0)
             Monitor.Wait(mylock);
    }

    // calls to A and B are balanced, proceed...
}
like image 26
Bradley Grainger Avatar answered Jul 17 '26 22:07

Bradley Grainger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!