简体   繁体   中英

How to kill a thread in asp.net core

I am writing an application using asp.net core in which I need to create a new thread as I have an always running loop. At some point, I need to mill this thread. In asp.net, Thread.abort was the solution, but it is removed in asp.net core. What is the alternative solution for this?

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.

The cleanest way to do this via a flag that is set by the "killing" thread and checked periodically by the thread that needs to be killed. Thread.Abort() is not a reliable way to do it; even the MSDN says Calling this method usually terminates the thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM