Understanding the worker services life cycle

.NET Core uses the definition of the BackgroundService class to identify a worker service. The BackgroundService class exposes three methods that represent the life cycle stages of the worker service:

namespace Microsoft.Extensions.Hosting
{
public abstract class BackgroundService : IHostedService, IDisposable
{
public virtual Task StartAsync(CancellationToken
cancellationToken);

protected abstract Task ExecuteAsync(CancellationToken
stoppingToken);

public virtual async Task StopAsync(CancellationToken
cancellationToken);
}
}

The preceding code is the abstract implementation of the BackgroundService class. The class implements both the IHostedService and IDisposable interfaces, and it exposes the following methods:

  • The StartAsync method represents the first stage of the life cycle of the worker. This method is called when the host is ready to run the worker service. It accepts a CancellationToken type parameter, which can be used to cancel the running task.
  • The ExecuteAsync method contains the core implementation of the BackgroundService class. This method is called once the IHostedService starts, and it returns a Task type that represents the status of the Task.
  • The StopAsync method is called when the hosted application is stopped gracefully.

This section provided an overview of the worker service life cycle methods. In the next section, we will see the hosting models available for the worker services in .NET Core. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.40.43