I’ve seen a number of examples that have a thread procedure that looks like this.
private void ThreadProc() { while (serviceStarted) { // do some work Thread.Sleep(new TimeSpan(0, 0, 5)); } Thread.CurrentThread.Abort(); }
Is the Abort() really necessary at the end?
There are number of arguments against calling Abort()
- Once the procedure exited – it is expected it has already cleaned up after itself.
- Calling
Abort()throws an exception, which is generally more resource intensive than just exiting a procedure.
I’d like to read an explanation for why this is or isn’t a good practice.
Calling
Thread.Abort()does raise an exception, and if you’re writing code that will be re-used (or part of a base library) it’s difficult for other developers to handleThreadAbortExcpetions.It’s explained in this article about Reliability Best Practices.
I’ve always heard that calling
Thread.Join()is a better way to do it, if you can wait until the thread is completed processing.I don’t know if anyone thinks it’s a good practice. It can cause deadlocks (because unmanaged resources aren’t properly cleaned up when you throw an exception)
Here’s another article about it, and other methods to deal with the issue.