3

Trying to implement downloadStringAsync() to prevent UI freezing for 10 seconds when downloading one byte of data. However, even though the download completes, it is freezing the UI just as if I used downloadString().

Here is my code:

    public void loadHTML()
    {
            WebClient client = new WebClient();

            // Specify that the DownloadStringCallback2 method gets called
            // when the download completes.
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(loadHTMLCallback);
            client.DownloadStringAsync(new Uri("http://www.example.com"));
            return;
    }

    public void loadHTMLCallback(Object sender, DownloadStringCompletedEventArgs e)
    {
        // If the request was not canceled and did not throw
        // an exception, display the resource.
        if (!e.Cancelled && e.Error == null)
        {
            string result = (string)e.Result;

            // Do cool stuff with result

        }
    }
Johnny
  • 373
  • 1
  • 6
  • 11
  • You're downloading *one byte of data* and noticing a significant delay, asynchronous or not? That is a huge problem in and of itself. Is that really all the code? If you're certain your internet connection doesn't work at a speed of 1 bps, I think you have other code there. Spawning a new thread to asynchronously download something should take about the same time as synchronously downloading one byte. It might also be that `DownloadStringAsync` synchronously checks headers, internet connectivity, or something before creating and executing the new thread, but that's a guess. – Ry- May 25 '11 at 02:58
  • Added `WebRequest.DefaultWebProxy = null;` and everything works fine now! It appears that auto proxy detection was the reason for the delay. – Johnny May 25 '11 at 03:46
  • Where's "the WebRequest.DefaultWebProxy = null;"? I could not find the property called "DefaultWebProxy" for WebRequest Class, @Johnny. – mxi1 Jun 05 '13 at 03:09

1 Answers1

2

Encountered the same problem, and found a solution. Quite complex discussion here: http://social.msdn.microsoft.com/Forums/en-US/a00dba00-5432-450b-9904-9d343c11888d/webclient-downloadstringasync-freeze-my-ui?forum=ncl

In short, the problem is web client is searching for proxy servers and hanging the app. The following solution helps:

WebClient webClient = new WebClient();
webClient.Proxy = null;
... Do whatever else ...
Wiseman
  • 1,059
  • 2
  • 13
  • 24