问题
According to
http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadprogresschanged.aspx,
OpenFileAsync should have DownloadProgressChanged firing whenever it makes progress.
I can't get it to fire at all. Fires fine with DownloadDataAsync and DownloadFileAsync instead though.
Here's a simple example:
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");
}
}
}
For me the DownloadProgressChanged event never fires, although change to DownloadFileAsync or DownloadDataAsync and it does.
回答1:
I've looked at the framework source and as far as I can tell the OpenReadAsync never touches the stuff that triggers DownloadProgressChanged.
It doesn't call GetBytes like DownloadDataAsync and DownloadFileAsync do, which is what in turn appears to be kicking off the event.
To work around it I've just used DownloadDataAsync instead, which does trigger the event and allows me to provide UI feedback for the download. It returns a byte array instead of the stream I needed, but that's not an issue.
So I'm assuming that it's MSDN that's wrong here, and OpenReadAsync doesn't trigger DownloadProgressChanged.
来源:https://stackoverflow.com/questions/2826190/does-webclient-openfileasync-fire-downloadprogresschanged