Reputation: 577
I have looked at all the solutions for this topic but still cannot seem to accomplish the stopping of a thread without using Thread.Abort(). Here is the code: Main class code that creates the the thread:
_pollingThread = new Thread(pollingThread);
_pollingThread.Start();
And here is the thread:
void _pollingThread()
{
while (continuePolling) //initially set to true
{
//do some things can take about 200ms to run
}
}
I next attempt to stop the thread from the main thread by setting continuePolling to false.
private void form1_FormClosing(object sender, FormClosingEventArgs e)
{
continuePolling = false;
Thread.Sleep(1000);
_pollingThread.Join(1000);
if (_pollingThread.IsAlive) //always alive!
{
_pollingThread.Abort;
}
}
Can someone tell me what I am doing wrong? Thanks
Upvotes: 0
Views: 1474
Reputation: 22038
Using Abort/Interrupt to stop a thread, is bad programming. You never knew what it did and what it didn't. There is one exception for that (like terminating hanging 3rd party code), even then consider it evil. You should use the ManualResetEvent
to tell the thread to terminate execution. The ManualResetEvent
is thread-safe and works great.
Here's an example:
public class MyThread
{
private ManualResetEvent _terminate = new ManualResetEvent(false);
private Thread _thread;
private void PollingThread()
{
while(!_terminate.WaitOne(0))
{
// do your stuff, if you want a pause after each loop,
// you should change the 0 of waitone. This way the
// termination isn't blocked when waiting
}
}
public MyThread()
{
_thread = new Thread(PollingThread);
_thread.Start();
}
public void Stop()
{
if(_thread != null)
{
_terminate.Set();
_thread.Join();
_thread = null;
}
}
}
Upvotes: 2
Reputation: 1187
continuePolling has to be declared volatile
, otherwise there is no guarantee that modifications in one thread will be seen in any other thread.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile
Alternatively you might consider using something like System.Timers.Timer
to run your polling action periodically.
Upvotes: 0