AsyncService Class
Base class for long-running services.
public abstract class AsyncService : IAsyncDisposable, IDisposableRemarks
This class differs from the BackgroundService class found in Microsoft.Extensions.Hosting in that it gives you more control over your service:
- you can, optionally, override the
AsyncService.SetupAsyncandAsyncService.TeardownAsyncmethods to separate setup and teardown from the core of your service; - you can either start your service in background by calling
AsyncService.Start, start it in background and wait for preliminary operations to complete by callingAsyncService.StartAndWaitAsync, or run it as a task by callingAsyncService.RunAsync; - you can use the
AsyncService.Stateproperty to know, at any time, if your service has been started, has finished starting, is stopping, has finished stopping, or has been disposed; - you can use the
AsyncService.DoneTokenproperty to get a cancellation token that will be canceled as soon as execution of the service stops, just before the teardown phase starts; - you can synchronize other tasks with your service by calling
AsyncService.WaitUntilStartedAsyncandAsyncService.WaitUntilStoppedAsync; - you can stop your service and let it complete in the background by calling
AsyncService.Stop, or stop and wait for completion by callingAsyncService.StopAndWaitAsync.
- Implements
Constructors
| Name | Description |
|---|---|
| AsyncService() | Initializes a new instance of the AsyncService class. |
AsyncService()
Initializes a new instance of the AsyncService class.
protected AsyncService()Properties
| Name | Description |
|---|---|
| DoneToken | Gets a CancellationToken that is canceled as soon as the service has finished executing (either successfully or with an exception) or has failed starting. |
| State | Gets the state of the service. |
DoneToken
Gets a CancellationToken that is canceled as soon as the service has finished executing (either successfully or with an exception) or has failed starting.
public CancellationToken DoneToken { get; }Property value
State
Gets the state of the service.
public AsyncServiceState State { get; }Methods
| Name | Description |
|---|---|
| Dispose() | Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. |
| DisposeAsync() | Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously. |
| DisposeResourcesAsync() | Asynchronously releases managed resources owned by this instance. Note that an instance of a class derived from AsyncService cannot directly own unmanaged resources. |
| ExecuteAsync(CancellationToken) | When overridden in a derived class, performs the actual operations the service is meant to carry out. |
| LogBeforeExecute() | Called just before calling the AsyncService.ExecuteAsync method. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogBeforeSetup() | Called just before calling the AsyncService.SetupAsync method. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogBeforeTeardown() | Called just before calling the AsyncService.TeardownAsync method. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogExecuteCanceled() | Called if the AsyncService.ExecuteAsync method throws OperationCanceledException and the service has been requested to stop. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogExecuteCompleted() | Called if the AsyncService.ExecuteAsync method terminates successfully. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogExecuteFailed(Exception) | Called if the AsyncService.ExecuteAsync method throws an exception, except when such exception indicates that service execution has been canceled. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogSetupCanceled() | Called if the AsyncService.SetupAsync method throws OperationCanceledException and the service has been requested to stop. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogSetupCompleted(bool) | Called if the AsyncService.SetupAsync method terminates successfully. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogSetupFailed(Exception) | Called if the AsyncService.SetupAsync method throws an exception, except when such exception indicates that service execution has been canceled. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogStateChanged(AsyncServiceState, AsyncServiceState) | Called whenever the AsyncService.State property changes. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogStopRequested(AsyncServiceState, AsyncServiceState, bool) | Called upon requesting that a service stops. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogTeardownCompleted() | Called if the AsyncService.TeardownAsync method terminates successfully. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| LogTeardownFailed(Exception) | Called if the AsyncService.TeardownAsync method throws an exception. This method must return as early as possible, must not throw, and should be only used for logging purposes. |
| RunAsync(CancellationToken) | Asynchronously runs an asynchronous service. |
| SetupAsync(CancellationToken) | When overridden in a derived class, performs asynchronous operations related to starting the service. |
| Start(CancellationToken) | Starts an asynchronous service, then returns while it continues to run in the background. |
| StartAndWaitAsync(CancellationToken) | Asynchronously starts an asynchronous service and waits for its AsyncService.SetupAsync method to complete. |
| Stop() | Stops an asynchronous service, without waiting for it to complete. If the service has not started yet, calling this method prevents it from starting. |
| StopAndWaitAsync() | Asynchronously stops an asynchronous service and waits for it to complete. If the service has not started yet, calling this method prevents it from starting. |
| TeardownAsync() | When overridden in a derived class, performs asynchronous operations related to stopping the service. |
| WaitUntilStartedAsync() | Asynchronously wait until an asynchronous service has started. |
| WaitUntilStoppedAsync() | Asynchronously wait until an asynchronous service has stopped. |
Dispose()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public void Dispose()Remarks
This method exists for compatibility with older libraries (e.g. DI containers) lacking support for IAsyncDisposable. It just calls AsyncService.DisposeAsync and waits for it synchronously.
If possible, you should use AsyncService.DisposeAsync instead of this method.
DisposeAsync()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
public ValueTask DisposeAsync()Returns
ValueTask A task that represents the asynchronous dispose operation.
Remarks
This method stops the service and waits for completion if it has been started, then calls AsyncService.DisposeResourcesAsync before releasing resources held by this class.
DisposeResourcesAsync()
Asynchronously releases managed resources owned by this instance.
Note that an instance of a class derived from AsyncService cannot directly own unmanaged resources.
protected virtual ValueTask DisposeResourcesAsync()ExecuteAsync(CancellationToken)
When overridden in a derived class, performs the actual operations the service is meant to carry out.
protected abstract Task ExecuteAsync(CancellationToken cancellationToken)LogBeforeExecute()
Called just before calling the AsyncService.ExecuteAsync method.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
protected virtual void LogBeforeExecute()LogBeforeSetup()
Called just before calling the AsyncService.SetupAsync method.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
protected virtual void LogBeforeSetup()LogBeforeTeardown()
Called just before calling the AsyncService.TeardownAsync method.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
protected virtual void LogBeforeTeardown()LogExecuteCanceled()
Called if the AsyncService.ExecuteAsync method throws OperationCanceledException and the service has been requested to stop.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
protected virtual void LogExecuteCanceled()LogExecuteCompleted()
Called if the AsyncService.ExecuteAsync method terminates successfully.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
protected virtual void LogExecuteCompleted()LogExecuteFailed(Exception)
Called if the AsyncService.ExecuteAsync method throws an exception, except when such exception indicates that service execution has been canceled.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
Parameters
exceptionException- The exception thrown by
AsyncService.ExecuteAsync.
LogSetupCanceled()
Called if the AsyncService.SetupAsync method throws OperationCanceledException and the service has been requested to stop.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
protected virtual void LogSetupCanceled()LogSetupCompleted(bool)
Called if the AsyncService.SetupAsync method terminates successfully.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
Parameters
successbooltrueif the operation was successful;falseotherwise.
LogSetupFailed(Exception)
Called if the AsyncService.SetupAsync method throws an exception, except when such exception indicates that service execution has been canceled.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
Parameters
exceptionException- The exception thrown by
AsyncService.SetupAsync.
LogStateChanged(AsyncServiceState, AsyncServiceState)
Called whenever the AsyncService.State property changes.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
protected virtual void LogStateChanged(AsyncServiceState oldState, AsyncServiceState newState)Parameters
oldStateAsyncServiceState- The old value of
AsyncService.State. newStateAsyncServiceState- The new value of
AsyncService.State.
LogStopRequested(AsyncServiceState, AsyncServiceState, bool)
Called upon requesting that a service stops.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
protected virtual void LogStopRequested(AsyncServiceState previousState, AsyncServiceState currentState, bool result)Parameters
previousStateAsyncServiceState- The value of the
AsyncService.Stateproperty before the stop request. currentStateAsyncServiceState- The value of the
AsyncService.Stateproperty after the stop request. resultbooltrueif the service was running when requested to stop;falseotherwise.
LogTeardownCompleted()
Called if the AsyncService.TeardownAsync method terminates successfully.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
protected virtual void LogTeardownCompleted()LogTeardownFailed(Exception)
Called if the AsyncService.TeardownAsync method throws an exception.
This method must return as early as possible, must not throw, and should be only used for logging purposes.
Parameters
exceptionException- The exception thrown by
AsyncService.TeardownAsync.
RunAsync(CancellationToken)
Asynchronously runs an asynchronous service.
public Task RunAsync(CancellationToken cancellationToken)Parameters
cancellationTokenCancellationToken- A
CancellationTokenused to stop the service.
Returns
Task A Task that will complete when the service has stopped.
Exceptions
InvalidOperationException- The service has already been started, either by calling
AsyncService.RunAsync,AsyncService.Start, orAsyncService.StartAndWaitAsync.
Remarks
Only one of AsyncService.RunAsync, AsyncService.Start, and AsyncService.StartAndWaitAsync may be called, at most once.
If the service was stopped before starting, the returned task is already completed.
SetupAsync(CancellationToken)
When overridden in a derived class, performs asynchronous operations related to starting the service.
protected virtual ValueTask<bool> SetupAsync(CancellationToken cancellationToken)Parameters
cancellationTokenCancellationToken- A
CancellationTokenused to stop the operation.
Returns
ValueTask<bool> A Task<bool> whose result will be true if the operation was successful, false otherwise.
Remarks
If the returned task completes with false, service execution will be stopped and neither AsyncService.ExecuteAsync nor AsyncService.TeardownAsync will be called.
Start(CancellationToken)
Starts an asynchronous service, then returns while it continues to run in the background.
public void Start(CancellationToken cancellationToken)Parameters
cancellationTokenCancellationToken- A
CancellationTokenused to stop the service.
Exceptions
InvalidOperationException- The service has already been started, either by calling
AsyncService.RunAsync,AsyncService.Start, orAsyncService.StartAndWaitAsync.
Remarks
Only one of AsyncService.RunAsync, AsyncService.Start, and AsyncService.StartAndWaitAsync may be called, at most once.
If your program needs to know the exact reason why a service stops or fails to start, do not use this method; call AsyncService.RunAsync from a separate task instead.
If the service was stopped before starting, this method does nothing.
StartAndWaitAsync(CancellationToken)
Asynchronously starts an asynchronous service and waits for its AsyncService.SetupAsync method to complete.
public Task<AsyncServiceSetupResult> StartAndWaitAsync(CancellationToken cancellationToken)Parameters
cancellationTokenCancellationToken- A
CancellationTokenused to stop the service.
Returns
Task<AsyncServiceSetupResult> A Task<AsyncServiceSetupResult> that will complete as soon as the service either has started or could not start.
Exceptions
InvalidOperationException- The service has already been started, either by calling
AsyncService.RunAsync,AsyncService.Start, orAsyncService.StartAndWaitAsync.
Remarks
Only one of AsyncService.RunAsync, AsyncService.Start, and AsyncService.StartAndWaitAsync may be called, at most once.
If AsyncService.SetupAsync throws an exception, the returned task throws the same exception, so its result is never AsyncServiceSetupResult.Faulted.
If your program needs to know the exact reason why a service stops, do not use this method; call AsyncService.RunAsync from a separate task instead.
If the service was stopped before starting, the returned task is already completed with AsyncServiceSetupResult.NotStarted.
See also
Stop()
StopAndWaitAsync()
Asynchronously stops an asynchronous service and waits for it to complete. If the service has not started yet, calling this method prevents it from starting.
Returns
Task<bool> A Task<bool> that will complete as soon as the service has finished stopping (in which case the result will be true), or immediately if the service was not running (in which case the result will be false).
TeardownAsync()
When overridden in a derived class, performs asynchronous operations related to stopping the service.
protected virtual ValueTask TeardownAsync()Returns
ValueTask A ValueTask that represents the ongoing operation.
Remarks
This method is called if and only if the Task returned by AsyncService.StartAndWaitAsync completes successfully, even if the service is prevented from starting afterwards (for example if the CancellationToken passed to AsyncService.StartAndWaitAsync is canceled after AsyncService.StartAndWaitAsync checks it for the last time).
WaitUntilStartedAsync()
Asynchronously wait until an asynchronous service has started.
public Task<AsyncServiceSetupResult> WaitUntilStartedAsync()Returns
Task<AsyncServiceSetupResult> A Task<AsyncServiceSetupResult> that will complete as soon as the service either has started or could not start.
Remarks
If none of AsyncService.RunAsync, AsyncService.Start, AsyncService.StartAndWaitAsync, and AsyncService.Stop have been called, the returned task will not complete until one of them is called.
If the service has already finished starting, or was stopped before starting, the returned task is already completed.
The returned task never throws. If AsyncService.SetupAsync throws an exception, the result is AsyncServiceSetupResult.Faulted, and the exception is thrown by AsyncService.RunAsync or AsyncService.StartAndWaitAsync instead.
WaitUntilStoppedAsync()
Asynchronously wait until an asynchronous service has stopped.
public Task WaitUntilStoppedAsync()Returns
Task A Task that will complete as soon as the service has started and then stopped, or until it has failed to start.
Remarks
If none of AsyncService.RunAsync, AsyncService.Start, AsyncService.StartAndWaitAsync, and AsyncService.Stop have been called, the returned task will not complete until one of them is called.
If the service has already stopped, the returned task is already completed.