且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IHostedService和Asp.net Core中计划任务的Task有什么区别?

更新时间:2023-02-15 23:11:43

通常是由于该过程的工作原理.我假设您没有将 Task.Run()放在控制器上,而是放在启动上.如果在控制器上使用它,它将仅在每个请求中启动一个新线程.

Generally is because of how the process works. I will assume that you don't place the Task.Run() on the controller but on the startup. If you use it on the controller it will simply start a new thread in each and every request.

ASP.NET Core的工作方式是启动一个进程,侦听传入的请求,并为每个请求创建一个新线程.请记住,使用任务运行创建新线程与在后台运行的线程不同.为了使其在后台运行,您需要一个新进程,而不是线程池中的线程.通常,这将是一个始终运行且永远不会释放给服务器其他请求的线程.

The way ASP.NET Core works is that it starts a process that listens for incoming request and for each request it creates a new thread for it. Remember that creating a new thread with task run is not the same as something running in the background. In order for it to run on the background you would require a new process not a thread from the thread pool. Generally this will be a thread that will always run and never be freed to server other requests.

此外,它是如此奇怪,以至于如果我使用Task.Delay都不会延迟任何延迟,而如果我使用Thread.Sleep则可以正常工作.

What's more, it is so strange that it won't delay any if I use the Task.Delay while it works well if I use the Thread.Sleep.

使用Task.Delay.它需要async关键字,并且不会阻塞线程.您可能没有使用 await 关键字.

Use Task.Delay. It requires the async keyword and it doesnt block the thread. You were probably not using the await keyword.

我想知道为什么没有人通过System.Threading.Tasks的任务实现它吗?

I wonder why no people achieve it by the Task of System.Threading.Tasks?

通常,您可以防御性地实现它,但重要的是对它的控制.每5分钟,您的cpu和io使用量就会猛增一次.但是,如果将应用程序拆分到同一主机的2个容器中,则可以控制每个容器具有多少CPU分配,从而使API的性能不会出现峰值.

Generally you could defently implement it but the important thing is the control you have over it. Every 5 minutes your cpu and io usage will spike. But if you split the application in 2 containers in the same host, you can control how much CPU allocation each container will have thus allowing you not to have spikes in performance for the API.

关于托管服务,从文档中可以看到ASP.NET Core启动Web服务器,然后在其他服务上启动IHostedService.这就是为什么它是首选.这是后台任务,而不是API线程池中的线程

About hosted service as you can see from the documentation ASP.NET Core starts a web server and then starts a IHostedService on a different service. Thats why it's preferred. It's a background task not a thread from the thread pool of your API

关于IHostedService,我错了,它不会启动新进程,但是您应该使用它只是因为它更易于管理,并且可以轻松交换新进程并以更加结构化的方式进行维护.

About the IHostedService I was wrong it doesn't start a new process but you should use it just because it's more manageable and it allows you swap a new process easily and maintain in a much more structured way.