Reputation: 10747
I have a local thread that is started on button-click event from the main thread. Its name is RegistrationThread
. I want to stop this thread on another stop button-click event.
How do I stop RegistrationThread
that is a local thread and I cannot access this thread by its name?
If I get the RegistrationThread
, then is it possible to suspend it? How to do this?
Upvotes: 3
Views: 392
Reputation: 48949
Aborting a thread is usually a measure of last resort. The reason is because it can cause a lot of unintended side-effects. The best practice is to allow the worker thread to end gracefully at predetermined safe points. This can be done correctly in many different ways. One of the simplest is to set a flag indicating to the worker thread that it should begin shutting down.
public class YourForm : Form
{
private volatile bool m_Stop = false;
private void StartButton_Click(object sender, EventArgs e)
{
var thread = new Thread(
() =>
{
while (...)
{
// Periodically poll the m_Stop flag.
if (m_Stop)
{
break;
}
}
});
thread.Start();
}
private void StopButton_Click(object sender, EventArgs e)
{
m_Stop = true;
}
}
If you really want to abort a thread then you could always save away a reference to the Thread
and then call Abort
on it from your stop button click event.
Upvotes: 1
Reputation: 1666
As far as I know, there's no nice way to find a thread by name, and Thread.Name is basically indended only to make debugging easier. Why not just hold onto a reference to the thread object instead?
It is possible to both stop (abort) and suspend another thread in .net, however neither are particularly advisable things to do.
It's generally considered bad form to call Thread.Abort. It's much safer to inform the code running in the other thread that it's time to abort and let it exit on its own at a safe point. Consider that the MSDN documentation only claims that calling Abort() on a thread "Usually" aborts the thread. This should be a sign that the API is really not meant to be used when results matter.
Suspending a thread is at least as evil as aborting it--if it's holding locks, suspending it could result in a deadlock. Even if your code contains no explicit locks, the .net runtime has many behind the scenes (e.g. for class initialization) that could get you in trouble. As a result, microsoft deprecated Thread.Suspend years ago.
Why don't you give us more information about what you're trying to do at a higher level and maybe we can help you find a better way.
Upvotes: 1