![]() ![]() If the task is completed then return it, this will bubble cancellation and failure to the caller _executeTask = ExecuteAsync ( _stoppingCts. CreateLinkedTokenSource ( cancellationToken ) Create linked token to allow cancelling executing task from provided token Public virtual Task StartAsync ( CancellationToken cancellationToken ) / Indicates that the start process has been aborted. / Triggered when the application host is ready to start the service. Protected abstract Task ExecuteAsync ( CancellationToken stoppingToken ) / A that represents the long running operations. / the lifetime of the long running operation(s) being performed. The implementation should return a task that represents / This method is called when the starts. Public virtual Task ExecuteTask => _executeTask / Will return if the background operation hasn't started. ![]() / Gets the Task that executes the background operation. Private CancellationTokenSource _stoppingCts Public abstract class BackgroundService : IHostedService, IDisposable / Base class for implementing a long running. NET Foundation licenses this file to you under the MIT license. NET Foundation under one or more agreements. So if the requirement is to poll continuously, then use the infinite loop until token is cancelled, for example, processing the messages from the queue as they arrive. The completion of ExecuteAsync method means that the service has finished its work. The cancellation can happen if you press ctrl + c or if the Host decides to stop the Hosted Services gracefully. The ExecuteAsync is an abstract method which will be called when the hosted service starts with the CancellationToken, which offers us to complete our work when Token cancellation is not requested. In other words, it is an excellent example of the Template Method Pattern. The BackgroundService encapsulates the implementation of StartAsync, StopAsync, creation of CancellationTokenSource and disposal of resources. BackgroundService īackgroundService is an abstract class, and implements IHostedService. There are two flavors of Hosted Service and abstract BackgroundService calls from let's explore these 3 things below below: 1. NET will move to the next service as soon as the task becomes awaitable. If your task is long-running, you can use a await Task.Yield() to unblock the StartAsync method. We will see a demo of such behavior later in the post. The StartAsync method should not block the execution because if multiple hosted services exist in the Host, the following services will not start until the first service finish the start.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |