没有CancellationToken可以取消C#任务吗? [英] Is it possible to cancel a C# Task without a CancellationToken?

查看:204
本文介绍了没有CancellationToken可以取消C#任务吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要取消一个返回Task的API调用,但是它不需要CancellationToken作为参数,并且我不能添加一个。

I'm need to cancel an API call that returns a Task, but it doesn't take a CancellationToken as a parameter, and I can't add one.

如何取消该任务?

在这种特殊情况下,我将Xamarin.Forms与Geocoder对象一起使用。

In this particular case, I'm using Xamarin.Forms with the Geocoder object.

 IEnumerable<Position> positions = await geo.GetPositionsForAddressAsync(address); 

该通话有时会花费很长时间。对于我的某些用例,用户只需导航到另一个屏幕,就不再需要该任务的结果。

That call can sometimes take a very long time. For some of my use cases, the user can just navigate to another screen, and that result of that task is no longer needed.

我还担心我的应用会睡眠,没有停止这个长期运行的任务,或者任务已经完成,并且需要不再有效的代码。

I also worry about my app going to sleep and not having this long running task stopped, or of the task completing and having need of code which is no longer valid.

推荐答案

有关此操作的最佳信息来自。NET并行编程博客上的斯蒂芬·图布

The best that I have read about doing this is from Stephen Toub on the "Parallel Programming with .NET" blog.

基本上,您可以创建自己的取消过载:

Basically you create your own cancellation 'overload':

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一起使用以调用异步函数:

And then use that with a try/catch to call your async function:

try 
{ 
    await op.WithCancellation(token); 
} 
catch(OperationCanceledException) 
{ 
    op.ContinueWith(t => /* handle eventual completion */); 
    … // whatever you want to do in the case of cancellation 
}

真的需要阅读他的博客文章...

Really need to read his blog posting...

这篇关于没有CancellationToken可以取消C#任务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆