25

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?

Julian
  • 30,223
  • 19
  • 105
  • 147
osynavets
  • 715
  • 1
  • 8
  • 18

1 Answers1

38

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.

So why is there a StartAsync and ExecuteAsync?

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.

In summary

  • When inheriting from BackgroundService, implement ExecuteAsync
  • When implementing IHostedService, implement StartAsync and StopAsync

Read more

Julian
  • 30,223
  • 19
  • 105
  • 147
  • 2
    You typically don't need to override `StartAsync`. It is there as a part of `IHostedService` implementation. All the work should be done in `ExecuteAsync`. – Alex Skalozub Feb 22 '20 at 20:31
  • Yes indeed! Updated my post to make it more clear. Thanks! – Julian Feb 22 '20 at 20:35
  • 1
    I would just be interested in your opinion - I think `BackgroundService` doesn't implement `IDisposable` properly as `CancellationTokenSource` is managed type so I would expect to see code like [this](https://stackoverflow.com/a/18337005/3242721). So if this class doesn't even implement `IDisposable` as it should, is there any point in using it rather than implementing `IHostedService`? – Michal Hosala Oct 20 '20 at 19:53