Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How often will DownloadProgressChangedEventHandler be called

Tags:

c#

.net

asp.net

I am using Webclient to download a file asynchronously. I am wondering how often is DownloadProgressChangedEventHandler get called? Can the user control it?

like image 669
user496949 Avatar asked Nov 10 '10 09:11

user496949


1 Answers

The following applies to the full .NET Framework, since your question is tagged ASP.NET. (Things might be different in Silverlight.)

Short answer: it's complex, the behaviour depends on various things including network performance characteristics, so it's inconsistent and you can't easily control it.

Long answer:

The event will typically be raised each time the underlying stream provided by the WebResponse invokes the completion callback for the BeginRead operation that WebClient uses to perform asynchronous downloads.

It looks like WebClient will typically attempt to read data in 64k chunks. However, streams are not required to return as much data as the called asked for - it's entirely possible that a call to BeginRead that requests 64k will return less. In fact, that's quite common for streams that read data from the network - they are likely to return a smaller amount of data shortly after it's available, rather than waiting until all 64k has come in.

So the exact answer depends on the stream in question, and may also depends to some extent on the nature and performance of the network connection.

WebClient uses WebRequest.Create to obtain the request/response implementation that will ultimately supply the stream, and that's an extensible mechanism - .NET has 5 built-in implementations of WebRequest and it offers an extensibility mechanism that lets you register additional handlers. And it's the specific WebRequest implementation that determines the nature of the stream.

So the frequency with which you get progress events is entirely up to the type of download you're doing - you can get different results depending on what sort of URL it is. (E.g., http vs ftp vs file, or whatever.)

I'm going to hazard a wild guess that you're using HTTP.

Even then, it's pretty complicated - the HttpWebResponse doesn't always use the same kind of stream. For example, it can sometimes return a stream derived from MemoryStream, sometimes it's of type ConnectStream...

So you can't say with any certainty what size chunks the underlying stream is likely to return because you can't even be sure what type of stream you're likely to get.

As for whether you can control it, about the only way you could would be to provide a custom WebRequest implementation for a custom URL scheme. But frankly, it's probably simpler just to write code that decides whether or not to do anything with any particular event rather than trying to change the frequency of the events.

like image 95
Ian Griffiths Avatar answered Nov 06 '22 19:11

Ian Griffiths