using System; using System.Threading; using System.Threading.Tasks; namespace GISTech.GISDataDownloader { internal static class TaskCancellationInternals { public static async Task CancelWithInternal(Task task, CancellationToken cancellationToken, bool swallowCancellationException = false) { TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(delegate(object s) { ((TaskCompletionSource)s).TrySetResult(result: true); }, taskCompletionSource)) { if (task != await Task.WhenAny(task, taskCompletionSource.Task)) { if (!swallowCancellationException) { throw new OperationCanceledException(cancellationToken); } return default(T); } } return await task; } public static async Task CancelWithInternal(Task task, CancellationToken cancellationToken, string message, bool swallowCancellationException = false) { TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(delegate(object s) { ((TaskCompletionSource)s).TrySetResult(result: true); }, taskCompletionSource)) { if (task != await Task.WhenAny(task, taskCompletionSource.Task)) { if (!swallowCancellationException) { throw new OperationCanceledException(message, cancellationToken); } return default(T); } } return await task; } public static async Task CancelWithInternal(Task task, CancellationToken cancellationToken, bool swallowCancellationException = false) { TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(delegate(object s) { ((TaskCompletionSource)s).TrySetResult(result: true); }, taskCompletionSource)) { if (task != await Task.WhenAny(task, taskCompletionSource.Task)) { if (swallowCancellationException) { throw new OperationCanceledException(cancellationToken); } return; } } await task; } public static async Task CancelWithInternal(Task task, CancellationToken cancellationToken, string message, bool swallowCancellationException = false) { TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(delegate(object s) { ((TaskCompletionSource)s).TrySetResult(result: true); }, taskCompletionSource)) { if (task != await Task.WhenAny(task, taskCompletionSource.Task)) { if (!swallowCancellationException) { throw new OperationCanceledException(message, cancellationToken); } return; } } await task; } } }