使用任务取消长时间运行的 IO/网络操作的好方法是什么? [英] What would be a good way to Cancel long running IO/Network operation using Tasks?

查看:38
本文介绍了使用任务取消长时间运行的 IO/网络操作的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究 .net 4.0 中的任务及其取消.我喜欢 TPL 尝试以合作的方式正确处理取消的事实.

I've been studying Tasks in .net 4.0 and their cancellation. I like the fact that TPL tries to deal with cancellation correctly in cooperative manner.

但是,如果任务内部的调用被阻塞并且需要很长时间,该怎么办?例如 IO/网络.

However, what should one do in situation where a call inside a task is blocking and takes a long time? For examle IO/Network.

显然取消写入会很危险.但这些都是例子.

Obviously cancelling writes would be dangerous. But those are examples.

示例:我将如何取消此操作?DownloadFile 可能需要很长时间.

Example: How would I cancel this? DownloadFile can take a long time.

Task.Factory.StartNew(() =>
    WebClient client = new WebClient();
    client.DownloadFile(url, localPath);
);

推荐答案

Task 支持取消标记.您可以创建 CancellationTokenSource 的实例并将其 Token 属性传递给您的 DownloadFile 方法.然后在代码中可以停止的点,检查令牌、IsCancellationRequested 属性以查看是否请求取消.

Task supports cancellation tokens. You can create an instance of CancellationTokenSource and pass it's Token property to your DownloadFile method. Then at points in your code where you can stop, check the tokens, IsCancellationRequested property to see if a cancel was requested.

您还应该将令牌传递给 StartNew(在方法之后).

You should also pass the token to StartNew (after the method).

要真正取消操作,您可以对取消令牌调用 Cancel 方法.

To actually cancel the operation you can call the Cancel method on the cancellation token.

查看这篇关于取消的 MSDN 文章

这篇关于使用任务取消长时间运行的 IO/网络操作的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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