How can I replace this semaphore with a monitor?
Posted
by Kurru
on Stack Overflow
See other posts from Stack Overflow
or by Kurru
Published on 2010-04-02T17:49:58Z
Indexed on
2010/04/02
17:53 UTC
Read the original article
Hit count: 619
Hi
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();
}
© Stack Overflow or respective owner