Migrating from the legacy .NET Framework I need to create a long time background process worker.
Looking at the documentation I found a BackgroundService
class, which is used for this kind of purpose. But I stumbled across two the same (for my point of view) methods ExecuteAsync()
and StartAsync()
Can somebody explain to me what the main difference between them? Is it some kind of segregation principle - we have a method for setting up data as the "constructor" and we have a method for actually doing things?
It defines two methods which are StartAsync(CancellationToken) and StopAsync(CancellationToken). StartAsync is nothing but a trigger when the application host to ready to start the service. It contains the logic to start background tasks.
It's a default, the StartAsync is virtual so you could override it. Please note that only StartAsync is public and ExecuteAsync protected (and abstract ). So from the outside StartAsync is called. If you create a subclass of BackgroundService , you must implement ExecuteAsync (because it's abstract ).
BackgroundService is a base class for implementing a long running IHostedService. ExecuteAsync(CancellationToken) is called to run the background service. The implementation returns a Task that represents the entire lifetime of the background service.
The BackgroundService token source is cancelled by the StopAsync method. So to cancel the CustomService async work you have to call the StopAsync method. This cancel token provided to the ExecuteAsync method as parameter.
The default behavior of the BackgroundService
is that StartAsync
calls ExecuteAsync
, see code. It's a default, the StartAsync
is virtual
so you could override it.
Please note that only StartAsync
is public
and ExecuteAsync
protected
(and abstract
). So from the outside StartAsync
is called
If you create a subclass of BackgroundService
, you must implement ExecuteAsync
(because it's abstract
). That should do your work. Also you could override StartAsync
(as it's virtual
), but that's only needed for special cases.
You could create a service by implementing IHostedService
. That interface has StartAsync
and StopAsync
.
BackgroundService
is an (base) implementation of IHostedService
, and could be used for long running tasks. This one defines the abstract ExecuteAsync
.
BackgroundService
, implement ExecuteAsync
IHostedService
, implement StartAsync
and StopAsync
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