Hi
I'm trying to safely stop a thread but as you might have guessed, I'm
failing at it.
GetCurrentThread seems to get the wrong handle, my form disappears when I
try to stop the thread and it looks like the thread keeps running.
Does anyone know how to get the correct handle or a better way to stop a
thread?
Before this, I used to check a bool in the loop to see if the loop should
break but this resulted sometimes in some long waiting times for the loop to
break;
using System;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Test
{
public delegate void ThreadStoppedHandler(object o, EventArgs e);
public delegate void ThreadStartedHandler(object o, EventArgs e);
public class ThreadControl
{
[DllImport("kernel32.dll")]
private static extern long GetExitCodeThread(long hThread, long
lpExitCode);
[DllImport("kernel32.dll")]
private static extern void ExitThread(long dwExitCode);
[DllImport("kernel32.dll")]
private static extern long GetCurrentThread();
private Thread _th;
private bool _running;
public event ThreadStoppedHandler ThreadStopped;
public event ThreadStartedHandler ThreadStarted;
public ThreadControl(ThreadStart ts) {
this._running = false;
this._th = new Thread(ts);
}
public bool IsRunning {
get{ return this._running; }
}
public ThreadPriority Priority {
get{ return this._th.Priority; }
set{ this._th.Priority = value; }
}
public void Start() {
if(!this._running) {
this._th.Start();
this._running = true;
if(this.ThreadStarted!=null)
this.ThreadStarted(this, new EventArgs());
} else {
this.Stop();
this.Start();
}
}
public void Stop(){
if(this._running)
ExitThread(GetExitCodeThread(GetCurrentThread(), 0));
this._running = false;
if(this.ThreadStopped!=null)
this.ThreadStopped(this, new EventArgs());
}
}
}
thanks