Difference between ExecuteAsync and StartAsync methods in BackgroundService .net core

Viewed 12895

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?

1 Answers

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

Related