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
SystemObject
  Neon.TasksAsyncPeriodicTask

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

The AsyncPeriodicTask type exposes the following members.

Constructors
  NameDescription
Public methodAsyncPeriodicTask
Constructs a periodic task.
Top
Properties
  NameDescription
Public propertyCancellationTokenSource
Returns the cancellation token.
Public propertyInterval
Returns the task interval.
Top
Methods
  NameDescription
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.)
Top
Remarks

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