我正在使用一个外部库,该库具有async
方法,但没有CancellationToken
的重载。
目前,我正在使用来自另一个StackOverflow问题的扩展方法来添加CancellationToken
:
public async static Task HandleCancellation(this Task asyncTask, CancellationToken cancellationToken)
{
// Create another task that completes as soon as cancellation is requested. https://dev59.com/PGMl5IYBdhLWcg3wHj5O#18672893
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
cancellationToken.Register(() =>
tcs.TrySetCanceled(), useSynchronizationContext: false);
Task cancellationTask = tcs.Task;
// Create a task that completes when either the async operation completes, or
// cancellation is requested.
Task readyTask = await Task.WhenAny(asyncTask, cancellationTask);
// In case of cancellation, register a continuation to observe any unhandled exceptions
// from the asynchronous operation (once it completes). In .NET 4.0, unobserved task
// exceptions would terminate the process.
if (readyTask == cancellationTask)
asyncTask.ContinueWith(_ => asyncTask.Exception,
TaskContinuationOptions.OnlyOnFaulted |
TaskContinuationOptions.ExecuteSynchronously);
await readyTask;
}
然而,底层任务仍然会执行完毕。这本来不是什么大问题,但有时底层任务永远不会完成,并且占用了我99%的CPU。
有没有办法在不终止进程的情况下“终止”这个任务?
Task
或Task<TResult>
的包装器。 - Theodor Zoulias