Wednesday, July 1, 2020

.NET Core–Backgroundservice lifetime

.NET Core 3 introduces a new worker template that uses the concept of a BackgroundService. The BackgroundService is a base class for implementing a long running IHostedService.

One important thing to be aware of is that the BackgroundService has a different lifetime than the host. This means that although a BackgroundService exits, it doesn’t mean that the host application will exit as well.

One way to guarantee that the host application stops when the BackgroundService exits, is by injecting the IHostApplicationLifetime in your service and call StopApplication():