13

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

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Ph0en1x
  • 9,943
  • 8
  • 48
  • 97
  • I'm sorry, I forgot that I have a power to close the question as duplicate. Very similar question: https://stackoverflow.com/q/36945253/213550 – VMAtm Sep 29 '17 at 00:40
  • 2
    @VMAtm - This is *not* a duplicate of [that](https://stackoverflow.com/q/36945253/213550) question. And after having come across that question and performing half a day of research. I find this is a very specific and appropriate question. – ttugates May 11 '18 at 20:14

3 Answers3

6

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 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.

SpruceMoose
  • 9,737
  • 4
  • 39
  • 53
0

I am researching this for days. I have a similar question here:

Asp.Net Core 2.0: Simple way to execute long running tasks and report progress

I have found an approach that uses QueueBackgroundWorkItem, but this is not available in Asp.Net Core.

The only thing I have found to be consistent in people's answers is that fire-and-forget is something that needs to be done outside IIS. In a Windows Service or something like Azure Web Jobs.

The only thing simple that free you from having to implement a distributed architecture is Hangfire, but it seems to be unrecommended for critical operations.

Jackson Mourão
  • 1,041
  • 10
  • 19
0

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.

Ph0en1x
  • 9,943
  • 8
  • 48
  • 97