In previous question of mine, someone had meantioned that using Semaphores were expensive in C# compared to using a monitor. So I ask this, how can I replace the semaphore in this code with a monitor?
I need function1 to return its value after function2 (in a separate thread) has been completed. I had replaced the Semaphore.WaitOne
with a Monitor.Wait
and the Semaphore.Release
with a Monitor.PulseAll
but the PulseAll
was being triggered before the Wait
causing the program to hang. Any idea how to avoid that race condition?
Semaphore semaphore = new Semaphore(0,1);
byte b;
public byte Function1()
{
// new thread starting in Function2;
semaphore.WaitOne();
return b;
}
public void Function2()
{
// do some thing
b = 0;
semaphore.Release();
}
You can do this with a WaitHandle instead of a Semaphore. This would be the simplest alternative, and perform better than a Semaphore:
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
byte b;
public byte Function1()
{
// new thread starting in Function2;
manualResetEvent.WaitOne();
return b;
}
public void Function2()
{
// do some thing
b = 0;
manualResetEvent.Set();
}
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