Skip to main content
 首页 » 编程设计

c#之WebClient.OpenFileAsync 是否触发 DownloadProgressChanged

2024年01月13日29zhwl

根据

http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadprogresschanged.aspx ,

OpenFileAsync 应该在它取得进展时触发 DownloadProgressChanged。

我根本无法让它开火。不过,使用 DownloadDataAsync 和 DownloadFileAsync 可以正常触发。

这是一个简单的例子:

using System; 
using System.Net; 
 
namespace ConsoleApplication1 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            WebClient client = new WebClient(); 
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted); 
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); 
            client.OpenReadAsync(new Uri("http://www.stackoverflow.com")); 
            Console.ReadKey(); 
        } 
 
        static void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
        { 
            Console.WriteLine("{0}% Downloaded", e.ProgressPercentage); 
        } 
 
        static void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
        { 
            Console.WriteLine("Open Read Completed"); 
        } 
    } 
} 

对我来说,DownloadProgressChanged 事件永远不会触发,但更改为 DownloadFileAsync 或 DownloadDataAsync 时它会触发。

请您参考如下方法:

我查看了框架源代码,据我所知,OpenReadAsync 从未触及触发 DownloadProgressChanged 的​​内容。

它不会像 DownloadDataAsync 和 DownloadFileAsync 那样调用 GetBytes,这反过来又似乎是事件的开始。

为了解决这个问题,我刚刚使用了 DownloadDataAsync,它确实会触发事件并允许我为下载提供 UI 反馈。它返回一个字节数组而不是我需要的流,但这不是问题。

所以我假设这里的错误是 MSDN,并且 OpenReadAsync 不会触发 DownloadProgressChanged。