Killing a .Net Thread

How to kill a thread in C# effectively?

Set an Abort flag to tell the thread is needs to terminate. Append a dummy record to the ServiceBroker queue. The WAITFOR then returns. The thread then checks its 'Abort' flag and, finding it set, deletes the dummy record from the queue and exits.

Another variant would be to add a 'real' poison-pill record to the specification for the table monitored by the ServiceBroker - an illegal record-number, or the like. That would avoid touching the thread/s at all in any direct manner - always a good thing:) This might be more complex, especially if each work thread is expeceted to notify upon actual termination, but would still be effective if the work threads, ServiceBroker and DB were all on different boxes. I added this as an edit because, having thought a bit more about it, it seems more flexible, after all, if the threads normally only communicate via. the DB, why not shut them down with only the DB? No Abort(), no Interrupt() and, hopefully, no lockup-generating Join().

How to kill a thread in asp.net core

Do not create your own thread for something like this!

There is a built-in method for using long running tasks in asp.core. You should read about this here.

You should create a class which derives from BackgroundService. Using this class is the easiest way to create a background-service that implements IHostedService. You can then add this to your program by calling services.AddHostedService<YourBackgroundService>() in the ConfigureServices method.

Note: In the page I linked, they use AddSingleton instead of AddHostedService. In .net core 2.1 and above you should use AddHostedService, not AddSingleton (there are some exceptions but we're talking in general here). See this answer for why that is.

If you implement your background-service like this, the shutdown of the additional thread will be handled for you. In your implementation of ExecuteAsync you need to just check if you should stop executing with the provided CancellationToken. You should also use asnyc implementations where possible and provide the CancellationToken there as well so the thread can end gracefully. You will never need to call Thread.Abort or even have access to the Thread itself; it's all done in the background for you.

Since this is not a direct answer to the question you asked but more of a correction of what you're probably doing wrong to get into this situation in the first place, I first wanted to make this a comment. However it's just too long and there are too many things to mention that's why I made this into an answer.

Hope this helps.

Kill thread, really!

There's only one way to safely kill a hung thread in your application: Environment.Exit And even that can fail if the thread is running kernel code.

It's best not to use third-party code that hangs. If you have no choice, then run it in a separate process.

C# killing a thread

Why don't you use a timer to schedule the task every ten minutes instead. That will run your code on a thread pool thread and thus you will not have to manage this yourself.

For more details see the System.Threading.Timer class.

How to terminate a thread in C#?

Thread.Abort will "kill" the thread, but this is roughly equivalent to:

Scenario: You want to turn off your computer

Solution: You strap dynamite to your computer, light it, and run.

It's FAR better to trigger an "exit condition", either via CancellationTokenSource.Cancel, setting some (safely accessed) "is running" bool, etc., and calling Thread.Join. This is more like:

Scenario: You want to turn off your computer

Solution: You click start, shut down, and wait until the computer powers down.

Killing a Thread in C#

Thread.Abort attempts to terminate the target thread by injecting an out-of-band (asynchronous) exception. It is unsafe because the exception gets injected at unpredictable points in the execution sequence. This can (and often does) lead to some type of corruption in the application domain because of interrupted writes to data structures.

Thread.Interrupt causes most blocking calls in the BCL (like Thread.Sleep, WaitHandle.WaitOne, etc.) to bailout immediately. Unlike aborting a thread, interrupting a thread can be made completely safe because the exception is injected at predictable points in the execution sequence. A crafty programmer can make sure these points are considered "safe points".

So, if "lots of code here" will respond to Thread.Interrupt then that might be an acceptable approach to use. But, I would like to steer you more towards the cooperative cancellation pattern. Basically, this means your code must periodically poll for a cancellation request. The TPL already has a framework in place for doing this via CancellationToken. But, you could easily accomplish the same thing with a ManualResetEvent or a simple volatile bool variable.

Now, if "lots of code here" is not under your control or if the cooperative cancellation pattern will not work (perhaps because you are using a faulty 3rd party library) then you pretty much have no other choice but to spin up a completely separate process to run the risky code. Use WCF to communicate with the process and if it does not respond then you can kill it without corrupting the main process. It is a lot of work, but it may be your only option.

How do I kill a thread if it takes too long in C#?

Check out this SO-solution using the IAsyncResult.AsyncWaitHandle.WaitOne() method

Killing a .NET 4 Task?

The Task class is designed, and intended, to use the new Cooperative Cancellation model of .NET 4 instead of relying on a destructive "abort" style of cancellation.

There is no direct way to cancel a Task (like Thread.Abort(), though that's very bad to use in any case), but there is an entire framework in place to provide the tooling to request that the Task cancel itself.



Related Topics



Leave a reply



Submit