This commit is contained in:
Connection Refused
2019-12-02 19:51:12 +08:00
commit b2ea730984
229 changed files with 86605 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
namespace System.Threading.Tasks
{
internal static class TaskExtensions
{
public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken, Action onCancel)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
{
if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false))
{
try
{
onCancel();
}
catch { }
throw new OperationCanceledException(cancellationToken);
}
}
return await task.ConfigureAwait(false);
}
}
}