5
string url = "http://google.com/index.html";
WebClient client = new WebClient();
Stopwatch sw = new Stopwatch();
sw.Start();
string text = client.DownloadString(url);
sw.Stop();
Console.WriteLine(sw.Elapsed);

Stopwatch says DownloadString method takes 13-15 seconds when first called, but repeated calls take sensible amounts of time. How does this happen and how do I fix it?

dtb
  • 213,145
  • 36
  • 401
  • 431
user1306322
  • 8,561
  • 18
  • 61
  • 122
  • 1
    possible duplicate of [.NET - DownloadStringAsync blocks thread for 14 seconds on first call](http://stackoverflow.com/questions/3128563/net-downloadstringasync-blocks-thread-for-14-seconds-on-first-call) – dtb May 13 '12 at 00:18

2 Answers2

9

There may be a couple of things that would cause a delay on the first call such as detecting proxy settings. Try setting the proxy to null:

client.Proxy = null;
nivlam
  • 3,223
  • 4
  • 30
  • 39
  • 4
    @user1306322 be sure to read the other answer; there's a reason for that delay. You could be making it impossible for some users to use your program if you just set that to null. Unless this is just an internal tool,, of course. – Andrew Barber May 13 '12 at 00:23
9

Your machine is configured to perform Automatic Proxy Detection.

You can disable it here:

Screenshot

Alternatively, you can manually override the proxy to be used by the WebClient; null means no proxy:

client.Proxy = null;

However, you should offer the user to configure a proxy in your application in this case, because some users have to use a proxy when accessing the Web.

dtb
  • 213,145
  • 36
  • 401
  • 431