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 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.
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().
Calling Abort() on one's own thread is safe, but apart from that it should generally be avoided because you can't be sure other threads will terminate gracefully. In many cases you don't need to abort the thread. Just let it finish and it will be reclaimed.
A thread will naturally self-terminate when it has no further work to do: when the logic it was executing completes.
Thread.Abort() causes a ThreadAbortException to be thrown on the current thread with the explicit purpose of rapidly terminating all execution on the thread. This is one of the special .NET exceptions which is "uncatchable": you can write a catch block but the exception will continue to be thrown after the catch block completes. This ensures there is no way an instruction to abort a thread can be stopped by subsequent user code.
Calling Thread.Abort() is generally seen as bad practice as there are more graceful ways to terminate the logic you are executing. Cancellation is better handled using a CancellationToken.
Interesting question. But I would advise against it since such a statement would prevent the method from being reused easily.
Related
Background
I have a Service abstraction. Each service has it own WorkItem. WorkItem able to start with some data. The service is limiting the excution time of WorkItem. Let's say that a single workitem can takes up to 60 seconds. After this, the Service should kill it.
This code migrated from the .NET Framework, I created a Thread object which run the Start(model) method. Then the code was something like:
Thread t = new Thread(workItem.Start, model);
t.start();
if (!t.Join(TimeSpan.FromSeconds(60)))
t.Abort();
The Thread.Abort was injecting an exception for the running thread, which lead it for immediately stop.
Now, I moved the code to dotnet core - as you may know, when you calling Thread.Abort() your getting the following message:
System.PlatformNotSupportedException: Thread abort is not supported on this platform.
at System.Threading.Thread.Abort()
at ...
The Goal
I want to limit the execution time of the WorkItem to specific amount of time. Note that this limitation should work also if you running code line like this:
Thread.Sleep(61000); // 61 seconds. should be stop after 60 seconds.
Progress
On the dotnet core world, it's seems like it's going to the Task related solution. So, I thought to use CancellationToken. But its seems like its impossible to watch the "Canceled" event and stop immediately. The examples I saw are using while (!canceled) loops, which cant stop long operations (like Thread.Sleep(1000000).
Question
How to do it right?
Update
I written this sample code:
public static bool ExecuteWithTimeLimit(TimeSpan timeSpan, Action codeBlock)
{
try
{
Task task = Task.Factory.StartNew(() => codeBlock());
if (!task.Wait(timeSpan))
{
// ABORT HERE!
Console.WriteLine("Time exceeded. Aborted!");
}
return task.IsCompleted;
}
catch (AggregateException ae)
{
throw ae.InnerExceptions[0];
}
}
And this Main file:
public static void Main(string[] args)
{
bool Completed = ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(2000), () =>
{
Console.WriteLine("start");
Thread.Sleep(3000);
Console.WriteLine("end");
});
Console.WriteLine($"Completed={Completed}");
Console.ReadLine();
}
Expected: "end" wont be printed to the screen. Actual: "end" printed. Is there any alternative that can kill a Task?
Use thread.Interrupt(); instead of Abort() method.
Without aborting the only solution is to poll the cancellation request often enough so after all the while (!canceled) solution you mentioned.
The examples I saw are using while (!canceled) loops, which cant stop long operations (like Thread.Sleep(1000000).
This is just partially true. For example, this can be re-written like this to be responsive:
var timeout = TimeSpan.FromSeconds(60);
var stopwatch = new Stopwatch();
stopwatch.Start();
while (!cancelToken.IsCancellationRequested
&& stopwatch.ElapsedMilliseconds < timeout)
{
Thread.Sleep(10);
}
Of course, not every task can be easily re-written to poll the cancellation like this. If you are in a deep call chain it can be a pain to check the cancellation at every level. For that reason you can also use the CancellationToken.ThrowIfCancellationRequested method, which will throw an OperationCanceledException if there was a cancel request. I usually tend to not throwing an exception just for myself and using it for control flow but cancellation is one of the areas where it can be justified.
This is solution has of course some limitations compared to Abort:
You will not able to cancel 3rd party routines, which don't support cancellation and you cannot refactor them
The OperationCanceledException can be swallowed easily, whereas ThreadAbortException was always re-raised at the end of the catch blocks so a 3rd part library could be aborted by a good chance even if contained general catch blocks.
Update:
If you are confident/desperate enough you can use the ThreadEx.Abort method, which calls the Thread.AbortInternal by reflection. Though it is not guaranteed it will be a long-living solution in .NET Core.
Though I don't completely agree with making Thread.Abort obsolete as it was a good last-chance tool for shutting down routines on which you didn't have influence otherwise, I'm also at the side abortion must be avoided at all costs as it can have nasty side effects. If you are the author of the whole code base it can be always avoided.
Update 2:
It seems that AbortInternal has been removed since then. At least current .NET Core source does not contain such a method.
You could use Thread.Interrupt(), which causes a ThreadInterruptedException() in the worker thread. You can catch the exception with a try catch, and after that safely join the thread with the main thread to clean up the worker thread. This would look like this:
Thread t = new Thread(workItem.Start, model);
t.Start();
// do other stuff or wait
t.Interrupt();
t.Join();
And the function of the worker thread looks like this:
try
{
// stuff the worker thread needs to do
}
catch (Exception e)
{
// go in here when interrupted
}
Waiting can then be implemented like this
Thread t = new Thread(workItem.Start, model);
t.Start();
if (!t.Join(TimeSpan.FromSeconds(60)))
{
t.Interrupt();
t.Join();
}
This is a way to (kind off) kill threads, but it is more clean to do it with CancelationTokens. I say kind of here as the thread won't get interrupted until it is blocked by the OS or some other block. So if the thread never blocks the exception is never thrown, and thus the thread might complete without ever being interrupted.
Four years later, there is now an equivalent in net7 !
Non-cooperative abortion of code execution:
ControlledExecution
Be careful, this method might corrupt the process, see documentation.
You can read about why and how such a method came back to .NET here:
https://github.com/dotnet/runtime/issues/41291
https://github.com/dotnet/runtime/discussions/66480
From experience: When Thread.Abort was made obsolete, we looked around. Thread.Interrupt was not of use to us.
Our final decision - refactor code to run some code in its own process and then we can use Process.Kill.
Background on why we do rude interruptions on code: Our system is used in manufacturing process automation and when someone hits an emergency stop button, the standard is to stop whatever the code is doing within 100ms. Our code sends a request to shutdown to the process (which may be running a third-party driver that does not listen for aborts) and, if the process does not shut down in 50ms, we do a Process.Kill(true). Frankly, for an emergency stop, we do not care if the system gets corrupted - we're going to rebuild the processes, anyway. In extreme situations, we will reboot the computer if we can save a life.
We also recognize that this is an edge situation and most code never needs to do rude interruptions.
Thread.Abort() used to work when carefully Handled. There is no discussion: Thread.Abort() is a dangerous API that throws ThreadAbortException at any random point deep in the call stack. Nevertheless production logs show that when carefully implemented Thread.Abort() doesn’t provoke any crash nor state corruption.
CancellationToken is nowadays the safe way to implement cancelable operations. But it is not a replacement for Thread.Abort(): it only supports co-operative cancellation scenarios, where the cancellable processing is responsible for periodically checking if it has been cancelled.
if(cancelToken.IsCancellationRequested){
throw new TaskCancelledException();
}
Update
As suggested by #Theodor, Same result can be achieved by using
cancelToken.ThrowIfCancellationRequested();
This function implements the same logic as above
you can then handle the thrown exception as follows
try
{
await YourTask(cancellationToken);
}
catch (OperationCanceledException ex) // includes TaskCanceledException
{
MessageBox.Show("Your submission was canceled.");
}
Quoting an answer by a dotnet/runtime collaborator, in a recent GitHub issue.
Aborting threads without asking them is a very dangerous practice and has not been supported by design in modern .NET since .NET Core 1.0, which is why I will close this issue.
The safe alternative is to pass CancellationTokens around in your thread and mark the points that are OK to abort, yourself by calling CancellationToken.ThrowIfCancellationRequested. A nice rule of thumb is to call this method at the beginning of a loop, but perhaps not all loops, you have to make a balance; if you call it too often performance will decrease, and if you call it too rarely code might not stop immediately.
If the thread you want to abort is performing I/O, you can cancel it by switching to asynchronous methods and the async and await keywords and passing to them that CancellationToken.
But either way your code needs some refactoring.
(teo-tsirpanis, Feb 18, 2022)
So it seems that officially there is no equivalent API in .NET Core and later.
Just my two cents.
As per my readings from this book Parallel Programming and Concurrency with C# 10 and .NET 6
Generally, destroying a managed thread is considered an unsafe practice. That is why .NET 6 no longer supports the Thread.Abort method. In .NET Framework, calling Thread.Abort on a thread would raise a ThreadAbortedException exception and stop the thread from running. Aborting threads was not made available in .NET Core or any of the newer versions of .NET. If some code needs to be forcibly stopped, it is recommended that you run it in a separate process from your other code and use Process.Kill to terminate the other process.
You can use Cancellation Tokens in conjenction with Tasks as well.
I'm working in a legacy project that has this exception handling code in many methods.
catch(ThreadAbortException e)
{
...
}
I don't see anywhere in the project Thread.Abort() or Thread.Interrupt() calls. Is it safe to delete all these ThreadAbortException handling or it is some other way that can be raised.
Well if answering specifically your question I would say that it would be better not to delete these exception handlers as it’s most likely that they were added by some developer trying to solve a problem. And I think there was a reason to add those handlers so if you just remove this code it can lead to appearing of some bugs again in the future.
Regarding the ThreadAbordException: I know for sure that it can be throwed not only with calling Thread.Abort() method when you are debugging (it might be a bug in VS, I’m not sure) and it forces your program to just crash silently. So depending on what’s inside of those handlers it could be possible that a developer was trying to solve such problem.
Also remember that you could be invoking methods of third-party libraries, web-services etc. in a separate thread, too. I’m not sure if they can throw such an exception but that’s a possible case to consider.
Official docs: "The exception that is thrown when a call is made to the Abort method." If you are completely sure there are no calls to Thread.Abort then you might as well erase those catch blocks.
EDIT: Be mindful that your code may be running in the context of an external app that may call Thread.Abort on your threads.
Not that it matters anyway as a ThreadAbortException can't really be handled as the CLR itself will rethrow it to actually kill the thread ASAP.
"Actually yes, a ThreadAbortException is special. Even if you handle it, it will be automatically re-thrown by the CLR at the end of the try/catch/finally. (As noted in the comments, it can be suppressed with ResetAbort but by that point the code smells like rotten fish.)"
- Read this question for more details: ThreadAbortException
Is the project running on a main thread and spinning up background worker threads? If the main thread exits while background threads are running, a ThreadAbortedException can occur on the background threads.
The catch statement could specifically handle this scenario, where no error actually occurred on the background thread, in a different manner than any other exception.
I want to run a long running opeartion in the background.
The requirements are:
The operation should run async to the calling thread.
The calling thread can wait on the operation to complete and obtain its result
Upon timeout, the operation should be aborted at once.
I would have used task, but there is no mechanism that I know of to kill the task dead cold.
Cancel token is not suitable for me, I would only kill a task if it gets stuck for unknown reason - (a bug) , this is a fail-safe mechanism.
Needles to say if the task is stuck, there is no use in requesting cancel.
Same goes for BackgroundWorker.
Is there anything more elagent than using a shared object between the calling thread and a background thread?
There is nothing more elegant than using a shared object, since using a shared object is the elegant way of doing this :)
You cant provide a generic way of killing a task safely: Since the killer thread does not have any clue of what the killee is doing when trying to kill it, this would potentially leave your object model in a "corrupted" state.
Thread.Abort() has been created to do that the cleanest way possible: By throwing an exception (which allows "finally" statements to dispose used resources, or running transactions disposal on killed thread). But this method can make the code throw an exception in unexpected location. It is highly not recommended.
nb: Thread.Abort() does not work in any case (example: wont work if your thread is running native code via a P/Invoke for instance)
Thus, the elegant solution is to write clean code, which can decide when it wants to be killed (via a cancellation token).
nb2: The ultimate "Thread.Abort()" which will work in any case, and which which will keep things isolated: Create a new AppDomain, run your killable code in this AppDomain (via remoting), and call AppDomain.Unload() when you want to stop everything.
This is a quite extreme solution, though.
The only way to kill a thread 'dead cold' that I know of is Thread.Abort, however, you will see a lot of answers to this related question, Killing a Thread C#, indicating that it is generally bad practice to use it, except in rare occasions.
Another option is to avoid trying to kill the task dead cold and implement better error handling in your task such that it gracefully handles exceptions and situations where it 'gets stuck'.
I have a thread thats analyzing a file and making transactional calls to the database, each transaction has a audit entry as part of its transaction. Is there anything vastly wrong with calling Thread.Abort() to stop the processing of the file? Rather than scatter ugly safe spots everywhere?
The file will be closed after the Abort call.
The obvious problem would be the risk of abandoning a transaction, which could cause blocking for an indeterminate time (or until timeout). But you could leave all sorts off mess - unrecoverable Monitor locks, semaphores, etc, memory leaks, etc.
In short: try as hard as possible to avoid having to abort a thread unless you know exactly what it is doing at the time. And the only way you could know what it is doing is if it is already in a known "safe spot" (to use your term) - so you might as well just throw an exception or something and let it raise itself in a managed way.
Best practice: only abort a thread when you are tearing down the process.
Try Thread.Interrupt() to force the thread to exit from its wait state.
MSDN page
So I know that you shouldn't use
Thread.Abort()
But I've never been given a good explanation. Is there a performance penalty or some hidden gotcha?
I know you can't ignore/swallow the ThreadAbortException (which makes sense)
In addition to all of the other good answers here, let me add that there is no guarantee whatsoever that a call to Thread.Abort will actually abort the thread in question, ever. It is possible (though not particularly easy) to "harden" a thread against being aborted. If, for example, you are aborting a thread because you believe it to be running hostile code then the hostile code could be resisting its own destruction.
If you have a long-running operation involving code that you do not own that must be taken down cleanly, the correct way to do this is to put that code in its own process, not its own thread. (And preferably in a highly security-restricted appdomain in that process.) You can then cleanly kill the process.
In short, Thread.Abort is at best indicative of bad design, possibly unreliable, and extremely dangerous. It should be avoided at all costs; the only time you should ever even consider aborting a thread is in some sort of "emergency shutdown" code where you are attempting to tear down an appdomain as cleanly as possible.
Because if you know that the thread is in some safe state in which it can be aborted, surely you can arrange better communication and have the thread exit cleanly.
The thread could have taken a lock and be in the middle of changing some shared state, and the Thread.Abort will undo the lock and leave the shared state corrupted.
It's easier to hurt yourself. As others have stated it raises an exception in the code, which can occur at any point. This might be fine if you expect this and have coded in a way that elegantly handles this exception at any point but some people dont:
Monitor.Enter(obj);
// some code - if exception is raised here, then the lock isn't released
Monitor.Exit(obj)
IDisposable someCriticalResource = GetResource();
// some code - if exception is raised here, then the object isn't disposed
someCriticalResource.Dispose();
Additionally if you're working with many people on a team unless you have good code reviews you cannot guarantee the quality of the code you'll be working with. Hence it is a good idea to preach the gospal of "no Thread.Abort()" than it is to get people to remember to write code that is robust against exceptions occuring anywhere within that code.
In short.
Any IDisposable object may not be disposed. Any locked object may not be unlocked. Anything that must be 100% performed will never be done.
When you call Thread.Abort() on another thread a ThreadAbortException is injected in the flow of that thread. If you're lucky the code will handled this well and abort in a well defined state. The problem is that you have no way to figure out if you will be lucky in every case, so if you prefer safe over sorry calling Thread.Abort on other threads is not a good idea.
Thread.Abort stops your thread in an uncontrolled fashion.
thread.Abort will throw an exception, which will cause that your thread stops immediatly.
What is wrong with that: in most cases, you want to gracefully stop the operation that you're performing. For instance, if you are executing an ACID operation, you might want to complete the current operation before ending the thread, so that your system remains in a stable state.
Thread.Abort rises an exception in the target thread. Target thread in the meantime can be performing some critical operations and rising an exception can break your application state.