The following code has the disadvantage that the worker thread will not be immediately terminated and will not take the final action after the main thread has reset waithandle. Instead, it will continue to do what it does until it reaches the next iteration of the loop, after which it will be locked indefinitely.
static void Main()
{
ManualResetEvent m = new ManualResetEvent(true); // or bool b = true
Thread thread = new Thread(new ThreadStart(delegate()
{
while(m.WaitOne()) //or while(b)
{
//do something
}
//perform final operation and exit
}));
thread.Start();
//do something
m.Reset(); //or b = false
//do something else
}
The following code has the disadvantage that it uses the Abort () method (there are people who say that it should be avoided at all costs), but it does exactly what I am looking for: make the workflow break out of the loop as soon as the main thread tells it to do this, perform the final operation and exit.
static void Main()
{
Thread thread = new Thread(new ThreadStart(delegate()
{
try
{
while(true)
{
}
}
catch(ThreadAbortException e)
{
}
}));
thread.Start();
thread.Abort();
}
, , ?
( , .net 4.5)