Reputation: 33059
I've got an abstract class that spawns an infinitely-looping thread in its constructor. What's the best way to make sure this thread is aborted when the class is done being used?
Should I implement IDisposable and simply this use this?
public void Dispose()
{
this.myThread.Abort();
}
I read that Abort() is evil. Should I instead have Dispose() set a private bool flag that the thread checks for true to exit its loop?
public void Dispose()
{
this.abort = true;
}
// in the thread's loop...
if (this.abort)
{
break;
}
Use the BackgroundWorker class instead?
Upvotes: 2
Views: 266
Reputation: 25031
I would like to expand on the answer provided by "lc" (which is otherwise great).
To use his approach you also need to mark the boolean flag as "volatile". That will introduce a "memory barrier" which will ensure that each time your background thread reads the variable that it will grab it from memory (as opposed to a register), and that when the variable gets written that the data gets transfered between CPU caches.
Upvotes: 4
Reputation: 13972
I'd suggest the BackgroundWorker method. It's relatively simple to implement and cleans up well.
Upvotes: 0
Reputation: 116458
Instead of having an infinite loop, use a boolean flag that can be set by the main class as the loop condition. When you're done, set the flag so the loop can gracefully exit. If you implement IDisposable
, set the flag and wait for the thread to terminate before returning.
You could implement a cancellable BackgroundWorker
class, but essentially it will accomplish the same thing.
If you really want, you can give it a window of time to finish itself after sending the signal. If it doesn't terminate, you can abort the thread like Windows does on shutdown.
The reason I believe Thread.Abort
is considered "evil" is that it leaves things in an undefined state. Unlike killing an entire process, however, the remaining threads continue to run and could run into problems.
Upvotes: 3