Task.Factory.FromAsync与CancellationTokenSource [英] Task.Factory.FromAsync with CancellationTokenSource

查看:256
本文介绍了Task.Factory.FromAsync与CancellationTokenSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码行用于从的NetworkStream异步读取:

I have the following line of code used to read asynchronously from a NetworkStream:

int bytesRead = await Task<int>.Factory.FromAsync(this.stream.BeginRead, this.stream.EndRead, buffer, 0, buffer.Length, null);



我想使它支持取消。我知道我可以取消使用CancellationTokenSource 的任务,但是我看不出有什么办法,我可以通过它来 TaskFactory.FromAsync() 。

I'd like to make it support cancellation. I see that I can cancel tasks using a CancellationTokenSource, however I don't see any way I can pass it to TaskFactory.FromAsync().

是否有可能使一个FromAsync() - 构建任务支持取消

Is it possible to make a FromAsync()-constructed task support cancellation?

编辑:我想取消一个已经运行的任务

I want to cancel a task that is already running.

推荐答案

梁咏琪,可惜FromAsync的语义性质表明你是只适应一个异步过程TPL的API(TPL = 微软的任务并行库

Gigi, unfortunately the semantic nature of FromAsync indicates that you are only adapting an asynchronous process to TPL's API (TPL = Microsoft's Task Parallel Library)

在本质上,TPL的ReadAsync控制异步行为本身,而FromAsync只有包装的行为(但不进行控制)。

In essence, TPL's ReadAsync controls the async behaviour itself, whilst FromAsync only wraps the behaviour (but doesn't control it).

现在,因为取消是TPL特定的结构,而且由于FromAsync对异步方法的内部工作没有控制被调用,那么就没有保证干净地取消任务,并确保所有资源被正确关闭(这就是为什么它被删去。如果你很好奇,就反编译的方法;))

Now since Cancellation is a TPL specific construct, and since FromAsync has no control on the inner workings of the async method being called, then there is no guaranteed way to cleanly cancel the task and ensure that all resources are closed correctly (which is why it was omitted. If you're curious, just decompile the method ;))

在这种情况下,它更有意义来包装实际的异步调用自己在一个正常的任务和检测OperationCancelled例外,这将让你有机会通过适当调用关闭流。

In these situations, it makes more sense to wrap the actual async call yourself in a normal task and detect the OperationCancelled exception, which will give you the opportunity to close your stream by making the appropriate calls.

总之,答案是,但没有什么从创建一个通用的重载的方法将选择正确的策略,以干净关闭根据其类型的流阻止你。

In short, the answer is no, but there is nothing stopping you from creating a generic overloaded method that will pick the correct strategy to cleanly close a stream depending on its type.

这篇关于Task.Factory.FromAsync与CancellationTokenSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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