开发者

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

开发者 https://www.devze.com 2023-03-20 18:00 出处:网络
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.

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.

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.

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

Task.Factory.StartNew(() =>
    WebClient client = new WebCli开发者_如何学运维ent();
    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. Then at points in your code where you can stop, check the tokens, IsCancellationRequested property to see if a cancel was requested.

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

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

Check out this MSDN article on cancellation

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号