Because without curly braces the _wh.WaitOne isn't part of the else statement. You probably want
else {
Console.WriteLine("In waiting state .... 1");
_wh.WaitOne();
}
Question
I was implementing "Producer/consumer queue" from Albahari's threading article link -->
In this article's work method below, if i add a console write like Console.WriteLine("In waiting state .... 1") before _wh.WaitOne(), then Signalling don't work and Consumer thread seems to be waiting indefinitely.
void Work()
{
while (true)
{
string task = null;
lock (_locker)
if (_tasks.Count > 0)
{
task = _tasks.Dequeue();
if (task == null) return;
}
if (task != null)
{
Console.WriteLine ("Performing task: " + task);
Thread.Sleep (1000); // simulate work...
}
else
**Console.WriteLine("In waiting state .... 1");**
_wh.WaitOne(); // No more tasks - wait for a signal
}
}
Can someone explain this behavior?
Solution
Because without curly braces the _wh.WaitOne isn't part of the else statement. You probably want
else {
Console.WriteLine("In waiting state .... 1");
_wh.WaitOne();
}