Hi EAI,
you can use Revents to indicate that all worker threads have finished
working before stopping the main thread. I would not recommend you aborting
the tread as that can lead to unforseen problems and indeterminate state,
rather if you can use something like a boolean to stop the threads.
Here is an example of three worker threads being run by the main UI thread,
the threee worker threads are all stopped before the main UI thread can
continue:
using System;
using System.Threadin g;
namespace ConsoleApplicat ion2
{
class Program
{
static void Main(string[] args)
{
MultiThreadClas s mtc = new MultiThreadClas s();
Console.WriteLi ne("STARTING THREADS");
mtc.Start();
Console.WriteLi ne("MAIN UI THREAD SLEEPING FOR 6 SECONDS");
Thread.Sleep(60 00);
Console.WriteLi ne("STOPPING THREADS");
mtc.Stop();
Console.WriteLi ne("ALL DONE");
Console.ReadLin e();
}
}
class MultiThreadClas s
{
private Thread _t1, _t2, _t3;
private ManualResetEven t _t1CompleteEven t,
_t2CompleteEven t,
_t3CompleteEven t;
private bool _continueWorkin g = true;
public MultiThreadClas s()
{
_t1 = new Thread(new ThreadStart(Thr ead1DoWork));
_t2 = new Thread(new ThreadStart(Thr ead2DoWork));
_t3 = new Thread(new ThreadStart(Thr ead3DoWork));
_t1CompleteEven t = new ManualResetEven t(false);
_t2CompleteEven t = new ManualResetEven t(false);
_t3CompleteEven t = new ManualResetEven t(false);
}
public void Start()
{
_t1.Start();
_t2.Start();
_t3.Start();
}
public void Stop()
{
WaitHandle[] handles = new WaitHandle[]{_t1CompleteEve nt,
_t2CompleteEven t,
_t3CompleteEven t};
_continueWorkin g = false;
//will wait here until all threads have finished
WaitHandle.Wait All(handles);
}
private void Thread1DoWork()
{
while (_continueWorki ng)
{
Console.WriteLi ne("Thread 1 working");
Thread.Sleep(10 00);
}
Console.WriteLi ne("Thread 1 stopped");
_t1CompleteEven t.Set();
}
private void Thread2DoWork()
{
while (_continueWorki ng)
{
Console.WriteLi ne("Thread 2 working");
Thread.Sleep(37 3);
}
Console.WriteLi ne("Thread 2 stopped");
_t2CompleteEven t.Set();
}
private void Thread3DoWork()
{
while (_continueWorki ng)
{
Console.WriteLi ne("Thread 3 working");
Thread.Sleep(55 5);
}
Console.WriteLi ne("Thread 3 stopped");
_t3CompleteEven t.Set();
}
}
}
Hope that helps
Mark R Dawson
http://www.markdawson.org
"EAI" wrote:
Hello All,
How to abort or make sure the child threads are aborted before aborting the
parent thread?
Thanks