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

假装没事ソ 提交于 2021-02-04 18:25:13

问题


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 WebClient();
    client.DownloadFile(url, localPath);
);

回答1:


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



来源:https://stackoverflow.com/questions/6705370/what-would-be-a-good-way-to-cancel-long-running-io-network-operation-using-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!