Refactoring
This commit is contained in:
590
AMWD.Common/Utilities/DelayedTask.cs
Normal file
590
AMWD.Common/Utilities/DelayedTask.cs
Normal file
@@ -0,0 +1,590 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AMWD.Common.Utilities
|
||||
{
|
||||
/// <summary>
|
||||
/// Implements an awaitable task that runs after a specified delay. The delay can be reset
|
||||
/// before and after the task has run. By resetting the delay, the task can be executed multiple
|
||||
/// times. The scheduled or executing or last executed task can be awaited, until the delay is
|
||||
/// reset. After that, the next execution can be awaited.
|
||||
/// </summary>
|
||||
public class DelayedTask
|
||||
{
|
||||
#region Data
|
||||
|
||||
/// <summary>
|
||||
/// The synchronisation object.
|
||||
/// </summary>
|
||||
protected readonly object syncObj = new();
|
||||
|
||||
/// <summary>
|
||||
/// The exception handler.
|
||||
/// </summary>
|
||||
protected Action<Exception> exceptionHandler;
|
||||
|
||||
private Timer timer;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the timer is running and an execution is scheduled. This
|
||||
/// is mutually exclusive to <see cref="IsRunning"/>.
|
||||
/// </summary>
|
||||
public bool IsWaitingToRun { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the action is currently running. This is mutually
|
||||
/// exclusive to <see cref="IsWaitingToRun"/>.
|
||||
/// </summary>
|
||||
public bool IsRunning { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether the action shall be executed again after the currently ongoing
|
||||
/// execution has completed.
|
||||
/// </summary>
|
||||
private bool nextRunPending;
|
||||
|
||||
/// <summary>
|
||||
/// Provides the <see cref="Task"/> for the <see cref="GetAwaiter"/> method.
|
||||
/// </summary>
|
||||
protected TaskCompletionSourceWrapper tcs;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the action to execute.
|
||||
/// </summary>
|
||||
protected Action Action { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the delay to wait before executing the action.
|
||||
/// </summary>
|
||||
public TimeSpan Delay { get; protected set; }
|
||||
|
||||
#endregion Data
|
||||
|
||||
#region Static methods
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new task instance that executes the specified action after the delay, but does
|
||||
/// not start it yet. Multiple executions are allowed when calling <see cref="Reset"/> after
|
||||
/// the executed was started.
|
||||
/// </summary>
|
||||
/// <param name="action">The action to execute.</param>
|
||||
/// <param name="delay">The delay.</param>
|
||||
/// <returns></returns>
|
||||
public static DelayedTask Create(Action action, TimeSpan delay)
|
||||
{
|
||||
return new DelayedTask { Action = action, Delay = delay };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new task instance that executes the specified action after the delay, but does
|
||||
/// not start it yet. Multiple executions are allowed when calling <see cref="Reset"/> after
|
||||
/// the executed was started.
|
||||
/// </summary>
|
||||
/// <param name="action">The action to execute.</param>
|
||||
/// <param name="delay">The delay.</param>
|
||||
/// <returns></returns>
|
||||
public static DelayedTaskWithResult<TResult> Create<TResult>(Func<TResult> action, TimeSpan delay)
|
||||
{
|
||||
return DelayedTaskWithResult<TResult>.Create(action, delay);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the specified action after the delay. Multiple executions are allowed when
|
||||
/// calling <see cref="Reset"/> after the executed was started.
|
||||
/// </summary>
|
||||
/// <param name="action">The action to execute.</param>
|
||||
/// <param name="delay">The delay.</param>
|
||||
/// <returns></returns>
|
||||
public static DelayedTask Run(Action action, TimeSpan delay)
|
||||
{
|
||||
return new DelayedTask { Action = action, Delay = delay }.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the specified action after the delay. Multiple executions are allowed when
|
||||
/// calling <see cref="Reset"/> after the executed was started.
|
||||
/// </summary>
|
||||
/// <param name="action">The action to execute.</param>
|
||||
/// <param name="delay">The delay.</param>
|
||||
/// <returns></returns>
|
||||
public static DelayedTaskWithResult<TResult> Run<TResult>(Func<TResult> action, TimeSpan delay)
|
||||
{
|
||||
return DelayedTaskWithResult<TResult>.Run(action, delay);
|
||||
}
|
||||
|
||||
#endregion Static methods
|
||||
|
||||
#region Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DelayedTask"/> class.
|
||||
/// </summary>
|
||||
protected DelayedTask()
|
||||
{
|
||||
tcs = CreateTcs();
|
||||
SetLastResult(tcs);
|
||||
}
|
||||
|
||||
#endregion Constructors
|
||||
|
||||
#region Public instance methods
|
||||
|
||||
/// <summary>
|
||||
/// Resets the delay and restarts the timer. If an execution is currently pending, it is
|
||||
/// postponed until the full delay has elapsed again. If no execution is pending, the action
|
||||
/// will be executed again after the delay.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
lock (syncObj)
|
||||
{
|
||||
if (!IsWaitingToRun && !IsRunning)
|
||||
{
|
||||
// Let callers wait for the next execution
|
||||
tcs = CreateTcs();
|
||||
}
|
||||
IsWaitingToRun = true;
|
||||
if (timer != null)
|
||||
{
|
||||
timer.Change(Delay, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
else
|
||||
{
|
||||
timer = new Timer(OnTimerCallback, null, Delay, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cancels the delay. Any pending executions are cleared. If the action was pending but not
|
||||
/// yet executing, this task is cancelled. If the action was not pending or is already
|
||||
/// executing, this task will be completed successfully after the action has completed.
|
||||
/// </summary>
|
||||
public void Cancel()
|
||||
{
|
||||
TaskCompletionSourceWrapper localTcs = null;
|
||||
lock (syncObj)
|
||||
{
|
||||
IsWaitingToRun = false;
|
||||
nextRunPending = false;
|
||||
timer?.Dispose();
|
||||
timer = null;
|
||||
if (!IsRunning)
|
||||
{
|
||||
localTcs = tcs;
|
||||
}
|
||||
}
|
||||
|
||||
// Complete the task (as cancelled) so that nobody needs to wait for an execution that
|
||||
// isn't currently scheduled
|
||||
localTcs?.TrySetCanceled();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts a pending execution immediately, not waiting for the timer to elapse.
|
||||
/// </summary>
|
||||
/// <returns>true, if an execution was started; otherwise, false.</returns>
|
||||
/// <remarks>
|
||||
/// A new execution is only started if one is currently waiting to run, or already running.
|
||||
/// In the former case, the execution is scheduled immediately with the timer; in the latter
|
||||
/// case, it is scheduled for when the currently running execution has completed. If an
|
||||
/// execution has been started (the method returned true), it can be awaited normally.
|
||||
/// </remarks>
|
||||
public bool ExecutePending()
|
||||
{
|
||||
lock (syncObj)
|
||||
{
|
||||
if (!IsWaitingToRun && !IsRunning)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
IsWaitingToRun = true;
|
||||
if (timer != null)
|
||||
{
|
||||
timer.Change(TimeSpan.Zero, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
else
|
||||
{
|
||||
timer = new Timer(OnTimerCallback, null, TimeSpan.Zero, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an awaiter used to await this <see cref="DelayedTask"/>.
|
||||
/// </summary>
|
||||
/// <returns>An awaiter instance.</returns>
|
||||
public TaskAwaiter GetAwaiter()
|
||||
{
|
||||
lock (syncObj)
|
||||
{
|
||||
return tcs.Task.GetAwaiter();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="System.Threading.Tasks.Task"/> that represents the current awaitable
|
||||
/// operation.
|
||||
/// </summary>
|
||||
public Task Task
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (syncObj)
|
||||
{
|
||||
return tcs.Task;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs an implicit conversion from <see cref="DelayedTask"/> to
|
||||
/// <see cref="System.Threading.Tasks.Task"/>.
|
||||
/// </summary>
|
||||
/// <param name="delayedTask">The <see cref="DelayedTask"/> instance to cast.</param>
|
||||
/// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the current
|
||||
/// awaitable operation.</returns>
|
||||
public static implicit operator Task(DelayedTask delayedTask) => delayedTask.Task;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the exception of the last execution. If the action has not yet thrown any
|
||||
/// exceptions, this will return null.
|
||||
/// </summary>
|
||||
public Exception Exception => Task.Exception;
|
||||
|
||||
/// <summary>
|
||||
/// Adds an unhandled exception handler to this <see cref="DelayedTask"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="exceptionHandler">The action that handles an exception.</param>
|
||||
/// <returns>The current instance.</returns>
|
||||
public DelayedTask WithExceptionHandler(Action<Exception> exceptionHandler)
|
||||
{
|
||||
this.exceptionHandler = exceptionHandler;
|
||||
return this;
|
||||
}
|
||||
|
||||
#endregion Public instance methods
|
||||
|
||||
#region Non-public methods
|
||||
|
||||
/// <summary>
|
||||
/// Starts the current instance after creating it.
|
||||
/// </summary>
|
||||
/// <returns>The current instance.</returns>
|
||||
protected DelayedTask Start()
|
||||
{
|
||||
tcs = CreateTcs();
|
||||
IsWaitingToRun = true;
|
||||
timer = new Timer(OnTimerCallback, null, Delay, Timeout.InfiniteTimeSpan);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="TaskCompletionSourceWrapper"/> instance.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected virtual TaskCompletionSourceWrapper CreateTcs()
|
||||
{
|
||||
return new TaskCompletionSourceWrapper<object>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when the timer has elapsed.
|
||||
/// </summary>
|
||||
/// <param name="state">Unused.</param>
|
||||
protected void OnTimerCallback(object state)
|
||||
{
|
||||
lock (syncObj)
|
||||
{
|
||||
if (!IsWaitingToRun)
|
||||
{
|
||||
// Already cancelled, do nothing
|
||||
return;
|
||||
}
|
||||
|
||||
IsWaitingToRun = false;
|
||||
if (IsRunning)
|
||||
{
|
||||
// Currently running, remember and do nothing for now
|
||||
nextRunPending = true;
|
||||
return;
|
||||
}
|
||||
IsRunning = true;
|
||||
}
|
||||
|
||||
// Run as long as there are pending executions and the instance has not been disposed of
|
||||
bool runAgain;
|
||||
TaskCompletionSourceWrapper localTcs = null;
|
||||
Exception exception = null;
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
exception = ex;
|
||||
lock (syncObj)
|
||||
{
|
||||
runAgain = false;
|
||||
IsRunning = false;
|
||||
nextRunPending = false;
|
||||
localTcs = tcs;
|
||||
if (!IsWaitingToRun)
|
||||
{
|
||||
timer?.Dispose();
|
||||
timer = null;
|
||||
}
|
||||
}
|
||||
exceptionHandler?.Invoke(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (syncObj)
|
||||
{
|
||||
runAgain = nextRunPending;
|
||||
IsRunning = runAgain;
|
||||
nextRunPending = false;
|
||||
if (!runAgain)
|
||||
{
|
||||
if (!IsWaitingToRun)
|
||||
{
|
||||
localTcs = tcs;
|
||||
timer?.Dispose();
|
||||
timer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
while (runAgain);
|
||||
|
||||
// Unblock waiters if not already waiting for the next execution.
|
||||
// This task can be awaited again after the Reset method has been called.
|
||||
if (exception != null)
|
||||
localTcs?.TrySetException(exception);
|
||||
else
|
||||
SetLastResult(localTcs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the action of the task.
|
||||
/// </summary>
|
||||
protected virtual void Run()
|
||||
{
|
||||
Action();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <see cref="TaskCompletionSourceWrapper"/> result from the last action.
|
||||
/// </summary>
|
||||
/// <param name="tcs">The <see cref="TaskCompletionSourceWrapper"/> to set the result of.</param>
|
||||
protected virtual void SetLastResult(TaskCompletionSourceWrapper tcs)
|
||||
{
|
||||
var myTcs = (TaskCompletionSourceWrapper<object>)tcs;
|
||||
myTcs?.TrySetResult(default);
|
||||
}
|
||||
|
||||
#endregion Non-public methods
|
||||
|
||||
#region Internal TaskCompletionSourceWrapper classes
|
||||
|
||||
/// <summary>
|
||||
/// Wraps a <see cref="TaskCompletionSource{TResult}"/> instance in a non-generic way to
|
||||
/// allow sharing it in the non-generic base class.
|
||||
/// </summary>
|
||||
protected abstract class TaskCompletionSourceWrapper
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the <see cref="Task{TResult}"/> of the <see cref="TaskCompletionSource{TResult}"/>.
|
||||
/// </summary>
|
||||
public abstract Task Task { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to transition the underlying <see cref="Task{TResult}"/> into the
|
||||
/// <see cref="TaskStatus.Faulted"/> state and binds it to a specified exception.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception to bind to this <see cref="Task{TResult}"/>.</param>
|
||||
/// <seealso cref="TaskCompletionSource{TResult}.TrySetException(Exception)"/>
|
||||
public abstract void TrySetException(Exception exception);
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to transition the underlying <see cref="Task{TResult}"/> into the
|
||||
/// <see cref="TaskStatus.Canceled"/> state.
|
||||
/// </summary>
|
||||
/// <seealso cref="TaskCompletionSource{TResult}.TrySetCanceled()"/>
|
||||
public abstract void TrySetCanceled();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A <see cref="TaskCompletionSourceWrapper"/> that provides a result value.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResult">The type of the result value.</typeparam>
|
||||
protected class TaskCompletionSourceWrapper<TResult> : TaskCompletionSourceWrapper
|
||||
{
|
||||
private readonly TaskCompletionSource<TResult> tcs;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="Task{TResult}"/> of the <see cref="TaskCompletionSource{TResult}"/>.
|
||||
/// </summary>
|
||||
public override Task Task => tcs.Task;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TaskCompletionSourceWrapper{TResult}"/> class.
|
||||
/// </summary>
|
||||
public TaskCompletionSourceWrapper()
|
||||
{
|
||||
tcs = new TaskCompletionSource<TResult>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to transition the underlying <see cref="Task{TResult}"/> into the
|
||||
/// <see cref="TaskStatus.RanToCompletion"/> state.
|
||||
/// </summary>
|
||||
/// <param name="result">The result value to bind to this <see cref="Task{TResult}"/>.</param>
|
||||
/// <seealso cref="TaskCompletionSource{TResult}.TrySetResult(TResult)"/>
|
||||
public void TrySetResult(TResult result)
|
||||
{
|
||||
tcs.TrySetResult(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to transition the underlying <see cref="Task{TResult}"/> into the
|
||||
/// <see cref="TaskStatus.Faulted"/> state and binds it to a specified exception.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception to bind to this <see cref="Task{TResult}"/>.</param>
|
||||
/// <seealso cref="TaskCompletionSource{TResult}.TrySetException(Exception)"/>
|
||||
public override void TrySetException(Exception exception)
|
||||
{
|
||||
tcs.TrySetException(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to transition the underlying <see cref="Task{TResult}"/> into the
|
||||
/// <see cref="TaskStatus.Canceled"/> state.
|
||||
/// </summary>
|
||||
/// <seealso cref="TaskCompletionSource{TResult}.TrySetCanceled()"/>
|
||||
public override void TrySetCanceled()
|
||||
{
|
||||
tcs.TrySetCanceled();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Internal TaskCompletionSourceWrapper classes
|
||||
}
|
||||
|
||||
#region Generic derived classes
|
||||
|
||||
/// <summary>
|
||||
/// Implements an awaitable task that runs after a specified delay. The delay can be reset
|
||||
/// before and after the task has run.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResult">The type of the return value of the action.</typeparam>
|
||||
public class DelayedTaskWithResult<TResult> : DelayedTask
|
||||
{
|
||||
/// <summary>
|
||||
/// The result of the last execution of the action.
|
||||
/// </summary>
|
||||
protected TResult lastResult;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the action to execute.
|
||||
/// </summary>
|
||||
protected new Func<TResult> Action { get; set; }
|
||||
|
||||
internal static DelayedTaskWithResult<TResult> Create(Func<TResult> action, TimeSpan delay)
|
||||
{
|
||||
return new DelayedTaskWithResult<TResult> { Action = action, Delay = delay };
|
||||
}
|
||||
|
||||
internal static DelayedTaskWithResult<TResult> Run(Func<TResult> action, TimeSpan delay)
|
||||
{
|
||||
return (DelayedTaskWithResult<TResult>)new DelayedTaskWithResult<TResult> { Action = action, Delay = delay }.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="DelayedTask.TaskCompletionSourceWrapper"/> instance.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected override TaskCompletionSourceWrapper CreateTcs()
|
||||
{
|
||||
return new TaskCompletionSourceWrapper<TResult>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the action of the task.
|
||||
/// </summary>
|
||||
protected override void Run()
|
||||
{
|
||||
lastResult = Action();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <see cref="DelayedTask.TaskCompletionSourceWrapper"/> result from the last action.
|
||||
/// </summary>
|
||||
/// <param name="tcs">The <see cref="DelayedTask.TaskCompletionSourceWrapper"/> to set the result of.</param>
|
||||
protected override void SetLastResult(TaskCompletionSourceWrapper tcs)
|
||||
{
|
||||
var myTcs = (TaskCompletionSourceWrapper<TResult>)tcs;
|
||||
myTcs?.TrySetResult(lastResult);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an awaiter used to await this <see cref="DelayedTask"/>.
|
||||
/// </summary>
|
||||
/// <returns>An awaiter instance.</returns>
|
||||
public new TaskAwaiter<TResult> GetAwaiter()
|
||||
{
|
||||
lock (syncObj)
|
||||
{
|
||||
var myTcs = (TaskCompletionSourceWrapper<TResult>)tcs;
|
||||
var myTask = (Task<TResult>)myTcs.Task;
|
||||
return myTask.GetAwaiter();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="Task{TResult}"/> that represents the current awaitable operation.
|
||||
/// </summary>
|
||||
public new Task<TResult> Task
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (syncObj)
|
||||
{
|
||||
var myTcs = (TaskCompletionSourceWrapper<TResult>)tcs;
|
||||
var myTask = (Task<TResult>)myTcs.Task;
|
||||
return myTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs an implicit conversion from <see cref="DelayedTaskWithResult{TResult}"/> to
|
||||
/// <see cref="Task{TResult}"/>.
|
||||
/// </summary>
|
||||
/// <param name="delayedTask">The <see cref="DelayedTaskWithResult{TResult}"/> instance to cast.</param>
|
||||
/// <returns>A <see cref="Task{TResult}"/> that represents the current awaitable operation.</returns>
|
||||
public static implicit operator Task<TResult>(DelayedTaskWithResult<TResult> delayedTask)
|
||||
{
|
||||
return delayedTask.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds an unhandled exception handler to this <see cref="DelayedTask"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="exceptionHandler">The action that handles an exception.</param>
|
||||
/// <returns>The current instance.</returns>
|
||||
public new DelayedTaskWithResult<TResult> WithExceptionHandler(Action<Exception> exceptionHandler)
|
||||
{
|
||||
this.exceptionHandler = exceptionHandler;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Generic derived classes
|
||||
}
|
||||
Reference in New Issue
Block a user