safely stopping threads

  • Thread starter Thread starter 2G
  • Start date Start date
2

2G

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
 
2G said:
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;

That's the safest approach to take though. You just need to check it more often. The only problem is if you've
got some really long-running blocking method calls.

You also need to make sure you do it safely in terms of the memory model.

See
http://www.pobox.com/~skeet/csharp/multithreading.html#worker.threads
 
Thanks for the reply Jon , I guess I'll stick to my old way then ;).


Jon Skeet said:
That's the safest approach to take though. You just need to check it more
often. The only problem is if you've
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top