Click or drag to resize

AsyncPeriodicTask Class

Implements a common asynchronous coding pattern where an asynchronous operation is performed periodically and cancellation and exceptions are handled cleanly.
Inheritance Hierarchy

Namespace:  Neon.Tasks
Assembly:  Neon.Common (in Neon.Common.dll) Version: 2.14.0
public sealed class AsyncPeriodicTask : IDisposable

The AsyncPeriodicTask type exposes the following members.

Public methodAsyncPeriodicTask
Constructs a periodic task.
Public propertyCancellationTokenSource
Returns the cancellation token.
Public propertyInterval
Returns the task interval.
Public methodDispose
Stops the task if it's running.
Public methodEquals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodRun
Asynchronously executes the task until it exits or is canceled.
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)

This class provides a nice way to implement the very common server side pattern where we need to periodically perform some operation until the operation signals that it's done or the task is canceled, while handling some of the messy exception handling details.

You'll use the AsyncPeriodicTask(TimeSpan, FuncTaskBoolean, FuncException, TaskBoolean, FuncTask, CancellationTokenSource) constructor to create a task, passing the task interval, asynchronous task handler and optional exception handler and cancellation token and then call Run to execute the task.

AsyncPeriodicTask will call the task handler, wait for the interval and then repeat. The task handler return false to continue running or true to signal that AsyncPeriodicTask should stop. AsyncPeriodicTask also monitors the cancellation token passed and watches for OperationCanceledException thrown by the task handler to stop itself.

The exception handler will be called for all exceptions thrown by the task handler except for OperationCanceledException exceptions as these signal that AsyncPeriodicTask should terminate. Exception handlers return false to continue running or true to signal that AsyncPeriodicTask should stop. stop.

Finally, an optional handler can be specified that will be called just before the AsyncPeriodicTask terminates.

Note Note
This class implements IDisposable and the task will be terminated when this is called.
See Also