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
It might be worth checking out this MSDN Developer blog on 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 withIHost
). 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With