What can cause issues when thread is aborted?
I need to use Thread.Abort() in my code because the thread runs complex code that have a lot of loops, objects and conditions.
I know that Thread.Abort() can lead to deadlock when using Monitor, also it can prevent resources from being released, but I can handle these problems.
I use IDisposable/using pattern or catch ThreadAbortException to guarantee that all resources are released and asynchronous operations are stopped.
The application seems to works fine now. But, since the code is pretty complex, I'm not sure if there could be some rare cases when aborting the thread can lead to memory leaks or unhandled exceptions.
Is there any .net classes (e.g. FileStream, Dictionary) that can cause problems if thread is aborted when their code are executed? Or some other issues that I should be aware of?
The problem with
Thread.Abortis that yourThreadAbortExceptioncan be thrown between any two instructions (almost).If you take some very simple code like:
And look at the generated C# and IL:
You can see that there's a couple of instructions between
CreateThingbeing called, and it entering thetryblock. There's a small window of opportunity where, ifThread.Abortis called right then, your object will not be disposed.So using
IDisposableandusingdoes not guarantee that your resources get freed in the face ofThread.Abort.There is a very good reason why
Thread.Abortwas removed from .NET Standard, and why you should useCancellationTokeninstead.You should use
CancellationToken, and your code should check whether it's been cancelled (usingCancellationToken.ThrowIfCancellationRequested()) at suitable, safe points.As an aside,
lockstatements use an overload ofMonitor.Enterwhich returns a boolean saying whether the lock was actually acquired, and:compiles to:
to avoid exactly this problem.
However, you don't get this luxury when using any other synchronization methods - only
lock- and so you can easily deadlock.