简体   繁体   English

使用任务取消长时间运行的 IO/网络操作的好方法是什么?

[英]What would be a good way to Cancel long running IO/Network operation using Tasks?

I've been studying Tasks in .net 4.0 and their cancellation.我一直在研究 .net 4.0 中的任务及其取消。 I like the fact that TPL tries to deal with cancellation correctly in cooperative manner.我喜欢 TPL 尝试以合作方式正确处理取消的事实。

However, what should one do in situation where a call inside a task is blocking and takes a long time?但是,在任务内部的调用被阻塞并且需要很长时间的情况下应该怎么做? For examle IO/Network.例如 IO/网络。

Obviously cancelling writes would be dangerous.显然取消写入将是危险的。 But those are examples.但这些都是例子。

Example: How would I cancel this?示例:我将如何取消这个? DownloadFile can take a long time. DownloadFile可能需要很长时间。

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

Task supports cancellation tokens.任务支持取消令牌。 You can create an instance of CancellationTokenSource and pass it's Token property to your DownloadFile method.您可以创建一个 CancellationTokenSource 实例并将其 Token 属性传递给您的 DownloadFile 方法。 Then at points in your code where you can stop, check the tokens, IsCancellationRequested property to see if a cancel was requested.然后在代码中可以停止的地方,检查令牌 IsCancellationRequested 属性以查看是否请求取消。

You should also pass the token to StartNew (after the method).您还应该将令牌传递给 StartNew(在方法之后)。

To actually cancel the operation you can call the Cancel method on the cancellation token.要实际取消操作,您可以在取消令牌上调用 Cancel 方法。

Check out this MSDN article on cancellation查看这篇关于取消的 MSDN 文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM