代码之家  ›  专栏  ›  技术社区  ›  Iain M Norman

webclient.openfileasync fire downloadProgressChanged

  •  2
  • Iain M Norman  · 技术社区  · 15 年前

    根据

    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,并且确实如此。

    1 回复  |  直到 15 年前
        1
  •  0
  •   Iain M Norman    15 年前

    我已经查看了框架源代码,据我所知,OpenReadAsync从不涉及触发DownloadProgressChanged的内容。

    它不调用像DownloadDataAsync和DownloadFileAsync这样的GetBytes,这反过来又似乎是启动事件的原因。

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

    所以我假设这里的msdn是错误的,openreadasync不会触发downloadProgressChanged。