Reputation: 7681
I have recently came across a multithreading pattern in legacy codebase, which relies on Thread.Abort()
method for canceling simultaneous requests to external systems. One of the bad consequences is that it is not easy to distinguish the timeout exceptions from the other exception types.
What are the other reasons not to use ThreadAbortException
s in multithreaded control flow?
Upvotes: 3
Views: 185
Reputation: 564771
What are the other reasons not to use ThreadAbortExceptions in multithreaded control flow?
Thread.Abort can leave the thread in a very odd state, which can be impossible to handle cleanly.
From the docs for Thread.Abort:
if one thread calls Abort on another thread, the abort interrupts whatever code is running. There is also a chance that a static constructor could be aborted. In rare cases, this might prevent instances of that class from being created in that application domain. In the .NET Framework versions 1.0 and 1.1, there is a chance the thread could abort while a finally block is running, in which case the finally block is aborted.
If you're working in multithreaded code, this can be even more dangerous, as it can trigger a deadlock. This is also documented:
The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur.
In general, it's far safer and cleaner to use the framework's cooperative cancellation model, and never call Thread.Abort
. Using CancellationToken
and CancellationTokenSource
allows you to design for proper cancellation in a way that's clean and where threads can properly handle their own cleanup.
Upvotes: 5