Last active
August 12, 2023 15:44
-
-
Save Sl4vP0weR/4e432f9e65318bc6b52e57875f0427fe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
public static class TaskExtensions | |
{ | |
public delegate void ExceptionCallback(Exception exception); | |
public delegate void CompleteCallback<in T>(T result); | |
public delegate void CompleteCallback(); | |
public static Task<T> WithResult<T>(this Task task, Func<Task, T> func) => | |
task.ContinueWith<T>(func); | |
public static Task<T> WithResult<T>(this Task task, Func<T> func) => | |
task.WithResult<T>(t => func()); | |
public static Task<T> WithResult<T>(this Task task, T value = default) => | |
task.WithResult(_ => value); | |
public static Task WithException(this Task task, Exception exception) => | |
task.WithResult<object>().WithException(exception); | |
public static async Task<T> WithException<T>(this Task<T> task, Exception exception) | |
{ | |
await task; | |
throw exception; | |
} | |
public static void Forget(this Task task, | |
CompleteCallback completeCallback = null, | |
ExceptionCallback exceptionCallback = null) => | |
task.WithResult<object>().Forget( | |
_ => completeCallback?.Invoke(), | |
exceptionCallback); | |
public static void Forget<T>(this Task<T> task, | |
CompleteCallback<T> completeCallback = null, | |
ExceptionCallback exceptionCallback = null) => | |
task.Subscribe(completeCallback, exceptionCallback); | |
public static Task Subscribe(this Task task, | |
CompleteCallback completeCallback = null, | |
ExceptionCallback exceptionCallback = null) => | |
task.WithResult<object>().Subscribe( | |
_ => completeCallback?.Invoke(), | |
exceptionCallback); | |
public static Task<T> Subscribe<T>(this Task<T> task, | |
CompleteCallback<T> completeCallback = null, | |
ExceptionCallback exceptionCallback = null) => | |
task.ContinueWith(t => | |
{ | |
if(t.IsFaulted) | |
exceptionCallback?.Invoke(t.Exception); | |
else if (t.IsCompleted) | |
{ | |
completeCallback?.Invoke(t.Result); | |
return t.Result; | |
} | |
return default; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment