14

I am using a WebClient to download a string from a website (which just contains plain text, nothing else), so I use the DownloadString method:

WebClient wc = new WebClient();
string str = wc.DownloadString("http://blah");

It works fine, but the problem is that the first time it downloads the string it takes a long time, like 5 seconds. After that it works fast. Why does this happen and how can overcome this problem?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
dnclem
  • 2,818
  • 15
  • 46
  • 64

3 Answers3

22

Setting the Proxy property of your WebClient object to null should eliminate the delays you're seeing. Alternatively if you've configured your system to use a proxy it can be retrieved with WebRequest.GetSystemWebProxy. The second method should eliminate the delay in either case.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
T3hc13h
  • 602
  • 6
  • 15
  • Neither `webClient.Proxy = WebRequest.GetSystemWebProxy()` nor `WebRequest.DefaultProxy` fix the problem, the delay still occurs. Setting it to `null` or `GlobalProxySelection.GetEmptyWebProxy()` _does_ work... but then the app can no longer be used on connections that require a proxy! Is there really no solution!? – BlueRaja - Danny Pflughoeft Oct 11 '15 at 04:53
6

I noticed the same thing. DotTrace shows it's spending the majority of its time enumerating proxy options:

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
4

Well, the first time it needs to do a DNS lookup and connect to the host - after that, within the same process it may well be reusing the same connection. For the very first request to anywhere, it may well also be trying to detect proxy settings etc.

If you want to see what's really happening at the network level to make it slow, I suggest you grab Wireshark and monitor the traffic with that.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194