AsyncService Class

Base class for long-running services.

public abstract class AsyncService : IAsyncDisposable, IDisposable

Remarks

This class differs from the BackgroundService class found in Microsoft.Extensions.Hosting in that it gives you more control over your service:

Implements

Constructors

NameDescription
AsyncService()Initializes a new instance of the AsyncService class.

AsyncService()

Initializes a new instance of the AsyncService class.

protected AsyncService()

Properties

NameDescription
DoneTokenGets a CancellationToken that is canceled as soon as the service has finished executing (either successfully or with an exception) or has failed starting.
StateGets 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

CancellationToken

State

Gets the state of the service.

public AsyncServiceState State { get; }

Property value

AsyncServiceState

See also

Methods

NameDescription
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()

Returns

ValueTask A ValueTask that represents the ongoing operation.

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)

Parameters

cancellationToken CancellationToken
A CancellationToken used to stop the service.

Returns

Task A Task representing the ongoing operation.

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.

protected virtual void LogExecuteFailed(Exception exception)

Parameters

exception Exception
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.

protected virtual void LogSetupCompleted(bool success)

Parameters

success bool
true if the operation was successful; false otherwise.

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.

protected virtual void LogSetupFailed(Exception exception)

Parameters

exception Exception
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

oldState AsyncServiceState
The old value of AsyncService.State.
newState AsyncServiceState
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

previousState AsyncServiceState
The value of the AsyncService.State property before the stop request.
currentState AsyncServiceState
The value of the AsyncService.State property after the stop request.
result bool
true if the service was running when requested to stop; false otherwise.

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.

protected virtual void LogTeardownFailed(Exception exception)

Parameters

exception Exception
The exception thrown by AsyncService.TeardownAsync.

RunAsync(CancellationToken)

Asynchronously runs an asynchronous service.

public Task RunAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken
A CancellationToken used 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, or AsyncService.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

cancellationToken CancellationToken
A CancellationToken used 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

cancellationToken CancellationToken
A CancellationToken used to stop the service.

Exceptions

InvalidOperationException
The service has already been started, either by calling AsyncService.RunAsync, AsyncService.Start, or AsyncService.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

cancellationToken CancellationToken
A CancellationToken used 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, or AsyncService.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()

Stops an asynchronous service, without waiting for it to complete. If the service has not started yet, calling this method prevents it from starting.

public bool Stop()

Returns

bool true if the service was running and has been requested to stop; false if the service was not running.

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.

public Task<bool> StopAndWaitAsync()

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.