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()
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.
Abort may prevent the execution of static constructors or the release of managed or unmanaged resources. For this reason, Thread. Abort always throws a PlatformNotSupportedException on .
Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. Calling this method usually terminates the thread.
By using thr. Abort(); statement, we can terminate the execution of the thread.
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 handle ThreadAbortExcpetion
s.
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.
Once the loop exits, the thread will terminate on its own. There is not need to abort the thread.
The CurrentThread.Abort
is not only superfluous, but genuinely harmful since it raises a ThreadAbortException
. If another thread attempts to Join()
your service loop thread, it will have to handle an exception unnecessarily. Your best bet is just to delete the line CurrentThread.Abort()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With