Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

native/canonical approach to Fire-and-forget in ASP.NET Core world

Doing some coding with websockets related, I found that's it's unclear at the moment, how to properly deal with long running background processes or tasks executed via fire-and-forget semantics (this is still correct for ASP.NET Core 2.0) since there could be some pitfalls with DI scope, app restarting, etc.

So it will be a nice to get some wise ideas how this kind of things need to be implemented in .NET Core world without fancy stuff like Hangfire

like image 251
Ph0en1x Avatar asked Aug 29 '17 17:08

Ph0en1x


2 Answers

It might be worth checking out this MSDN Developer blog on IHostedService and the BackgroundService class:

  • Implementing background tasks in .NET Core 2.x webapps or microservices with IHostedService and the BackgroundService class

Summary:

The IHostedService interface provides a convenient way to start background tasks in an ASP.NET Core web application (in .NET Core 2.0) or in any process/host (starting in .NET Core 2.1 with IHost). Its main benefit is the opportunity you get with the graceful cancellation to clean-up code of your background tasks when the host itself is shutting down.

like image 173
SpruceMoose Avatar answered Sep 22 '22 03:09

SpruceMoose


Looks like this was a pretty common question to dotnet team. So they finally write a document explaining how to implement this based on IHostedService interface. So since .NET Core 2.0 correct way of implementing this described in this article.

Background tasks with hosted services in ASP.NET Core


I rewrite my own code with a proposed approach based on queue and queue listener. In many cases, it's really very similar to example proposed in the article, but still, If there will be quite a lot of guys who interested I could extract my solution to GitHub and deploy as a NuGet package.

like image 22
Ph0en1x Avatar answered Sep 20 '22 03:09

Ph0en1x