90 lines
2.7 KiB
C#
90 lines
2.7 KiB
C#
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace GISTech.GISDataDownloader
|
|
{
|
|
internal static class TaskCancellationInternals
|
|
{
|
|
public static async Task<T> CancelWithInternal<T>(Task<T> task, CancellationToken cancellationToken, bool swallowCancellationException = false)
|
|
{
|
|
TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
|
|
using (cancellationToken.Register(delegate(object s)
|
|
{
|
|
((TaskCompletionSource<bool>)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<T> CancelWithInternal<T>(Task<T> task, CancellationToken cancellationToken, string message, bool swallowCancellationException = false)
|
|
{
|
|
TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
|
|
using (cancellationToken.Register(delegate(object s)
|
|
{
|
|
((TaskCompletionSource<bool>)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<bool> taskCompletionSource = new TaskCompletionSource<bool>();
|
|
using (cancellationToken.Register(delegate(object s)
|
|
{
|
|
((TaskCompletionSource<bool>)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<bool> taskCompletionSource = new TaskCompletionSource<bool>();
|
|
using (cancellationToken.Register(delegate(object s)
|
|
{
|
|
((TaskCompletionSource<bool>)s).TrySetResult(result: true);
|
|
}, taskCompletionSource))
|
|
{
|
|
if (task != await Task.WhenAny(task, taskCompletionSource.Task))
|
|
{
|
|
if (!swallowCancellationException)
|
|
{
|
|
throw new OperationCanceledException(message, cancellationToken);
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
await task;
|
|
}
|
|
}
|
|
}
|