using System;
using System.Threading.Tasks;
namespace QFSW.QC.Actions
{
///
/// Converts an async Task into an action.
///
public class Async : ICommandAction
{
private readonly Task _task;
public bool IsFinished => _task.IsCompleted ||
_task.IsCanceled ||
_task.IsFaulted;
public bool StartsIdle => false;
/// The async Task to convert.
public Async(Task task)
{
_task = task;
}
public void Start(ActionContext context) { }
public void Finalize(ActionContext context)
{
if (_task.IsFaulted)
{
throw _task.Exception.InnerException;
}
if (_task.IsCanceled)
{
throw new TaskCanceledException();
}
}
}
///
/// Converts an async Task into an action.
///
/// The return type of the Task to convert.
public class Async : ICommandAction
{
private readonly Task _task;
private readonly Action _onResult;
public bool IsFinished => _task.IsCompleted ||
_task.IsCanceled ||
_task.IsFaulted;
public bool StartsIdle => false;
/// The async Task to convert.
/// The action to invoke when the Task completes.
public Async(Task task, Action onResult)
{
_task = task;
_onResult = onResult;
}
public void Start(ActionContext context) { }
public void Finalize(ActionContext context)
{
if (_task.IsFaulted)
{
throw _task.Exception.InnerException;
}
if (_task.IsCanceled)
{
throw new TaskCanceledException();
}
_onResult(_task.Result);
}
}
}