/// <summary> /// Await a <see cref="Task{TResult}"/> /// </summary> /// <typeparam name="TResult">The type of the result</typeparam> /// <param name="resultHandler"></param> /// <param name="task">The task to wait</param> public static async void Await <TResult>( this IExternalEventResultHandler <TResult> resultHandler, Task <TResult> task) { try { var result = await task; if (task.IsCompleted) { resultHandler.SetResult(result); } if (task.IsCanceled) { resultHandler.Cancel(); } if (task.IsFaulted) { resultHandler.ThrowException(task.Exception ?? new Exception("Unknown Exception")); } } catch (Exception e) { resultHandler.ThrowException(e); } }
/// <summary> /// Wait for an sync delegate to complete /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="resultHandler"></param> /// <param name="function"></param> public static void Wait <TResult>(this IExternalEventResultHandler <TResult> resultHandler, Func <TResult> function) { try { var result = function(); resultHandler.SetResult(result); } catch (Exception e) { resultHandler.ThrowException(e); } }
/// <summary> /// Await a <see cref="Task{TResult}"/> /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="resultHandler"></param> /// <param name="source"></param> /// <returns></returns> public static IExternalEventResultHandler <TResult> Await <TResult>( this IExternalEventResultHandler <TResult> resultHandler, Task <TResult> source) { source.ContinueWith(task => { if (task.IsCompleted) { resultHandler.SetResult(task.Result); } else if (task.IsFaulted) { resultHandler.ThrowException(task.Exception ?? new Exception("Unknown Exception")); } else if (task.IsCanceled) { resultHandler.Cancel(); } }); return(resultHandler); }