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.
CountdownEvent may be what you are looking for.
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With