Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To CurrentThread.Abort or not to CurrentThread.Abort

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()

  1. Once the procedure exited - it is expected it has already cleaned up after itself.
  2. 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.

like image 200
Mike Daniels Avatar asked Nov 26 '08 19:11

Mike Daniels


People also ask

Why is thread abort obsolete?

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 .

What does thread abort do?

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.

How do I stop my AC threading?

By using thr. Abort(); statement, we can terminate the execution of the thread.


2 Answers

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 ThreadAbortExcpetions.

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.

like image 159
Zachary Yates Avatar answered Oct 08 '22 06:10

Zachary Yates


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().

like image 40
Juliet Avatar answered Oct 08 '22 05:10

Juliet