简体   繁体   English

我如何确定WebClient.DownloadFileTaskAsync是否已取消?

[英]How do i find out if WebClient.DownloadFileTaskAsync was cancelled?

How do i know if a call to WebClient.DownloadFileTaskAsync was cancelled? 我怎么知道是否取消了对WebClient.DownloadFileTaskAsync的调用?

My method call is like this: 我的方法调用是这样的:

WebClient webclient = new WebClient();
await webClient.DownloadFileTaskAsync(uri, filename);

The call is then cancelled elsewhere with: 然后通过以下方式取消呼叫:

webClient.CancelAsync();

When the await continues, how do i know if it was succesful or was cancelled? 当等待继续进行时,我如何知道它成功还是被取消?

When using await , then an OperationCanceledException object will be thrown if the object that you are awaiting on is canceled. 使用await ,如果取消了您正在等待的对象,则将抛出OperationCanceledException对象。

If the task is not canceled, execution will resume normally after the await point. 如果未取消任务,将在await点之后正常恢复执行。

If I remember well, you can simply inspect the Task object that you awaited for. 如果我还记得的话,您可以简单地检查等待的Task对象。

WebClient webclient = new WebClient();
var task = webClient.DownloadFileTaskAsync(uri, filename);
await task;

later, you can inspect it: 以后,您可以检查它:

task.Status
task.IsCancelled
task.IsCompleted  -> task.Result
task.IsFaulted    -> task.Exception

MSDN:Task MSDN:任务

...or just check Jean Hominal's excellent point on that topic (upon task failure, the await simply throws instead of continuing). ...或只是查看让·霍米纳尔(Jean Hominal)在该主题上出色观点(在任务失败时, 等待只会引发而不是继续)。

As the DownloadFileTaskAsync method returns a Task you should be able to simply look at the IsCancelled property. DownloadFileTaskAsync方法返回一个Task时,您应该能够简单地查看IsCancelled属性。

if (task.IsCancelled) {
     // Task was cancelled.
}

See this link: 看到这个链接:

http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx

IsCancelled - Gets whether this Task instance has completed execution due to being canceled. IsCancelled-获取此Task实例是否由于取消而已完成执行。

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

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