Is WebClient.DownloadFileAsync really this slow?
I'm using the DownloadFileAsync
method of WebClient
to download some files from a server, and I can't help but notice that in my informal testing of my code within VS2010, it blocks for about 3 seconds while it starts, which, in my opinion kind of defeats the purpose in the first place.
Here is the relevant snippet of code:
WebClient downloader = new WebClient();
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(updateDownloadProgress);
downloader.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(downloadCompleted);
var current_map = map_downloads[0];//string with filename, map_downloads is List<string>
var path = System.IO.Path.GetTempFileName();
downloaded_maps.Add(path);//adding the temp file to a List<string>
downloader.DownloadFileAsync(new Uri(MAP_BASE + current_map), path); //MAP_BASE is a string containing the base url
I'm using DownloadFileAsync
to keep the UI from blocking while the application downloads a ~100 MB file. Obviously if the UI blocks for 3 seconds while the call starts, that diminishes the utility somewhat, if not entirely.
I'm relatively inexperi开发者_StackOverflowenced with C#/.Net (I did a bunch of .Net 2.0 stuff about 3-4 years ago, IIRC, but I'm basically relearning it now).
In addition to what Nav says, it looks like the problem is web proxy autodetection, see this answer: Why is this WebRequest code slow?
I tested it and it now works without any significant delay during the first call.
I read somewhere that DownloadFileAsync actually checks the DNS name in a blocking thread, hence why you may be getting the slowdown. If you put the IP in directly, there should be no blocking. Found that piece of info here: http://www.csharp-examples.net/download-files/
Have you figured out if the delay is in your app, or on the network? To find out if the destination server is slow, run Wireshark and see when the first response is received after request is sent. Maybe that is where the delay occurs?
Also, if this is part of a big application, then the first time will always be slow due to startup costs. If you really want to get a good measurement, measure the total time required for the 1st invocation, and for the 2nd through the 10th invocation. From this you can find out if the delay is in startup costs, or everytime.
in ASP.NET, using async method has no meaning if thread role expected from aysnc method.
When I start webclient async it always joins when the main thread finishes(before rendering aspx).
great article about the topic : http://weblogs.asp.net/gunnarpeipman/archive/2010/09/07/making-asynchronous-calls-to-web-services-during-asp-net-page-processing.aspx
here are other info about it : WebClient async callback not called in ASP.NET MVC
精彩评论