mirror of
https://github.com/netchx/netch.git
synced 2026-03-26 18:49:46 +08:00
done
This commit is contained in:
25
Netch/3rd/DnsClient.NET/TaskExtensions.cs
Normal file
25
Netch/3rd/DnsClient.NET/TaskExtensions.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user