我需要取消返回 Task 的 API 调用,但它没有将 CancellationToken 作为参数,我无法添加。
如何取消该任务?
在这种特殊情况下,我将 Xamarin.Forms 与 Geocoder 对象一起使用。
IEnumerable<Position> positions = await geo.GetPositionsForAddressAsync(address);
该调用有时会花费很长时间。对于我的一些用例,用户只需导航到另一个屏幕,不再需要该任务的结果。
我还担心我的应用程序会进入休眠状态并且没有停止这个长时间运行的任务,或者担心任务完成并且需要不再有效的代码。
最佳答案
我读到的关于这样做的最好的文章来自 Stephen Toub on the "Parallel Programming with .NET" blog .
基本上您可以创建自己的取消“重载”:
public static async Task<T> WithCancellation<T>(
this Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using(cancellationToken.Register(
s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
if (task != await Task.WhenAny(task, tcs.Task))
throw new OperationCanceledException(cancellationToken);
return await task;
}
然后将其与 try/catch 一起使用以调用您的异步函数:
try
{
await op.WithCancellation(token);
}
catch(OperationCanceledException)
{
op.ContinueWith(t => /* handle eventual completion */);
… // whatever you want to do in the case of cancellation
}
真的需要阅读他的博文......
关于c# - 是否可以在没有 CancellationToken 的情况下取消 C# 任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32344143/