c# - WebClient.OpenFileAsync 是否触发 DownloadProgressChanged

标签 c# .net webclient

根据

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。

关于c# - WebClient.OpenFileAsync 是否触发 DownloadProgressChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2826190/

相关文章:

c# - 使用 MVVM 的 DataTemplate ListBox 绑定(bind)和触发器中的 CheckBox

c# - 使用 LINQ 对项目进行分组和组合

c# - 我如何在字符串c#中获取某个索引之后的所有内容

c# - 多个 WebClient 不工作?

C# - 如何进行 HTTP 调用

c# - 在与此域关联的配置文件中找不到部分 'caSTLe'

c# - 以 TreeView 样式显示

c# - SaveFileDialog 设置默认路径和文件类型?

c# - 线程 - ResetEvent 和 WebClient

c# - TransactionScope,sql 事件探查器的开始事务在哪里?