我需要取消返回任务的 API 调用,但它不采用 CancellationToken 作为参数,而且我无法添加一个。
我怎样才能取消该任务?
在这种特殊情况下,我将 Xamarin.Forms 与 Geocoder 对象一起使用。
IEnumerable<Position> positions = await geo.GetPositionsForAddressAsync(address);
该呼叫有时可能需要很长时间。对于我的一些用例,用户只需导航到另一个屏幕,并且不再需要该任务的结果。
我还担心我的应用程序会进入睡眠状态并且不会停止这个长时间运行的任务,或者任务完成并需要不再有效的代码。
我读到的关于这样做的最好的资料来自Stephen Toub 在“.NET 并行编程”博客上 http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx.
基本上,您可以创建自己的取消“过载”:
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
}
真的需要阅读他的博客文章......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)