Hi,
Maybe this approach will work for you:
When writing a Windows Forms application, I tend to use the
Application.ApplicationExit
event as the trigger to terminate any running threads that the application needed.
How you actually terminate the thread is up to you and the design, but I generally build a kill-switch into the thread-methods's loop. Once that is set to false, the thread method terminates on it's next pass through the loop.
PS: if you have a
Monitor.Wait()
or
AutoResetEvent.WaitOne()
holding your thread suspended while it waits for work, don't forget to signal the thread when you want it to stop.
eg:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
class ThreadTerminateExample
{
private Thread _thread;
private bool _runFlag = true;
public ThreadTerminateExample()
{
_thread = new Thread((ThreadStart)ThreadMethod);
_thread.Start();
Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
}
void Application_ApplicationExit(object sender, EventArgs e)
{
StopThread();
}
private void ThreadMethod()
{
while (_runFlag)
{
Console.WriteLine("Doing Some Work");
Thread.Sleep(1000);
}
}
private void StopThread()
{
_runFlag = false;
_thread.Join(2000);
_thread = null;
}
}