The answer is don't use a
bool
to synchronize threads, use an
EventWaitHandle
, for example a
AutoResetEvent
.
This shows how one thread can be made to wait for another:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadApplication {
class Program {
static void Main(string[] args) {
var are = new AutoResetEvent(false);
var producer = Task.Factory.StartNew(() => {
Console.WriteLine("I am producer!");
Thread.Sleep(1000);
Console.WriteLine("Producer is done!");
are.Set();
});
var consumer = Task.Factory.StartNew(() => {
Console.WriteLine("I am consumer, I will wait for producer!");
are.WaitOne();
Console.WriteLine("Producer is done, so now consumer is done!");
});
Task.WaitAll(producer, consumer);
}
}
}
Hope this helps,
Fredrik