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.Threading;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
MultiThreadClass mtc = new MultiThreadClass();
Console.WriteLine("STARTING THREADS");
mtc.Start();
Console.WriteLine("MAIN UI THREAD SLEEPING FOR 6 SECONDS");
Thread.Sleep(6000);
Console.WriteLine("STOPPING THREADS");
mtc.Stop();
Console.WriteLine("ALL DONE");
Console.ReadLine();
}
}
class MultiThreadClass
{
private Thread _t1, _t2, _t3;
private ManualResetEvent _t1CompleteEvent,
_t2CompleteEvent,
_t3CompleteEvent;
private bool _continueWorking = true;
public MultiThreadClass()
{
_t1 = new Thread(new ThreadStart(Thread1DoWork));
_t2 = new Thread(new ThreadStart(Thread2DoWork));
_t3 = new Thread(new ThreadStart(Thread3DoWork));
_t1CompleteEvent = new ManualResetEvent(false);
_t2CompleteEvent = new ManualResetEvent(false);
_t3CompleteEvent = new ManualResetEvent(false);
}
public void Start()
{
_t1.Start();
_t2.Start();
_t3.Start();
}
public void Stop()
{
WaitHandle[] handles = new WaitHandle[]{_t1CompleteEvent,
_t2CompleteEvent,
_t3CompleteEvent};
_continueWorking = false;
//will wait here until all threads have finished
WaitHandle.WaitAll(handles);
}
private void Thread1DoWork()
{
while (_continueWorking)
{
Console.WriteLine("Thread 1 working");
Thread.Sleep(1000);
}
Console.WriteLine("Thread 1 stopped");
_t1CompleteEvent.Set();
}
private void Thread2DoWork()
{
while (_continueWorking)
{
Console.WriteLine("Thread 2 working");
Thread.Sleep(373);
}
Console.WriteLine("Thread 2 stopped");
_t2CompleteEvent.Set();
}
private void Thread3DoWork()
{
while (_continueWorking)
{
Console.WriteLine("Thread 3 working");
Thread.Sleep(555);
}
Console.WriteLine("Thread 3 stopped");
_t3CompleteEvent.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