gpt4 book ai didi

c# - DownloadFileAsync 抛出未处理的异常?

转载 作者:行者123 更新时间:2023-11-30 18:33:45 25 4
gpt4 key购买 nike

我正在使用 C# 中的 WebClient 下载文件。我正在使用 client.DownloadFileAsnyc()。在过去这工作得很好,任何异常都会被捕获并在完成处理程序中返回 (AsyncCompletedEventArgs.Error)

但现在我发现,如果我在下载期间用完目标位置的空间,则会抛出 IOExcption 并导致应用程序崩溃。有谁知道为什么这不会在完成处理程序中被捕获和返回?
注意:我还尝试将 DownloadFileAsync 行放在 try catch 中。还是不行

代码如下:

_client = new WebClient();
_client.DownloadProgressChanged += ProgressChanged;
_client.DownloadFileCompleted += DownloadComplete;
_client.DownloadFileAsync(new Uri(url), Destination);

private void DownloadComplete(object sender, AsyncCompletedEventArgs args)
{
}

这是在 .NET 3.5 下编译的。

最佳答案

MSDN docs for System.ComponentModel表明您的 DownloadFileCompleted 处理程序确实应该收到异常,但显然这不会发生在这里。您可以尝试 Hook WebClient 上的其他一些 *Completed 事件,看看它是否被发送到那里。

在任何情况下,您都不会捕获异常,因为它不会发生在执行 try/catch block 的线程上。

当您使用异步 api 函数(通常指任何以“Async”或“Begin”结尾的函数名称)时,实际操作发生在线程池中,而不是在您启动操作的线程上。围绕在 try/catch 中的操作将不会捕获后台线程上的失败。

要正确捕获应用程序中的所有异常,您可以安装 global exception handler每当抛出未在程序其他地方捕获的异常时调用。

解决此行为的一种简单方法是使用同步 client.DownloadFile() 函数,然后从后台线程调用该函数,这样您就不会阻塞程序的主线程。这是一个演示它的简单示例:

// create a thread function to download a file synchronously
function DoDownload(object state){
List<String> st = (List<String>)(state);
String uri = st[0];
String fname = st[1];
try {
client.DownloadFile(uri, fname);
} catch {
// you'll catch the exception here because the
// try/catch is on the same thread that is doing the downloading
}
}

// somewhere else, when you want to actually start the download:
String uri = "http://example.com/the_file.txt";
string theFileName = "destination.txt";
List<String> st = new List<String>{ theUri, theFileName };
ThreadPool.QueueUserWorkItem(DoDownload, st);

请注意,此示例有点滥用系统线程池,尤其是当您将其用于下载需要超过一秒左右的大文件时。如果您正在下载较大的文件,或者同时下载许多文件,您绝对不应该这样做。

关于c# - DownloadFileAsync 抛出未处理的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17067915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com