My particular scenario: - Main thread starts a worker thread. - Main thread needs to block itself until either worker thread is completed (yeah funny) or worker thread itself informs main thread to go on
Alright, so what I did in main thread:
wokerThread.Start(lockObj);
lock(lockObj)
Monitor.Wait(lockObj);
Somewhere in worker thread:
if(mainThreadShouldGoOn)
lock(lockObj)
Monitor.Pulse(lockObj);
Also, at the end of worker thread:
lock(lockObj)
Monitor.Pulse(lockObj);
So far, it's working perfect. But is it a good solution? Is there a better one?
EDIT:
What if I do it like this in main thread:
Monitor.Enter(lockObj);
workerThread.Start(lockObj);
Monitor.Wait(lockObj);
And worker looks like this:
void Worker(object lockObj)
{
Monitor.Enter(lockObj);
...
...
...
if(mainThreadShouldGoOn)
{
Monitor.Pulse(lockObj);
Monitor.Exit(lockObj);
}
...
...
...
if(!mainThreadShouldGoOn)
{
Monitor.Pulse(lockObj);
Monitor.Exit(lockObj);
}
}