none
Why the WebRequest.Create method is extremely slow? RRS feed

  • Question

  • I have implemented a simple method that periodically polls a service in order to get the public IP address. The method WebRequest.Create takes nearly 10 seconds to create the HttpWebRequest for the first time, while on subsequent calls the same instance is created almost instantaneously. What are the reasons for this behavior?

    Below is the source code of my method.

    Stopwatch sw = new Stopwatch();
    
    while (true)
    {
        Console.WriteLine("(HttpWebRequest)WebRequest.Create...");
    
        sw.Restart();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://whatismyipaddress.com/");
        sw.Stop();
    
        Console.WriteLine("HttpWebRequest was created in {0} ms", sw.ElapsedMilliseconds);
    
        request.Proxy = null;
    
        sw.Restart();
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            sw.Stop();
            Console.WriteLine("Response was received in {0} ms", sw.ElapsedMilliseconds);
    
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string responseStr = sr.ReadToEnd().Trim();
    
            string ipStr = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(responseStr)[0].ToString();
            IPAddress address = IPAddress.Parse(ipStr);
    
            Console.WriteLine("IP: {0}", address.ToString());
        }
    
        Console.WriteLine();
        Thread.Sleep(5000);
    }

    Thanks a lot for your suggestions!

    Vincenzo

    Monday, November 4, 2013 9:46 PM

Answers

All replies

  • The first time you create a request for a given server, it will do a DNS lookup for the IP address.  Subsequent calls will be cached, which may explain the behavior.


    Reed Copsey, Jr. - http://reedcopsey.com - If a post answers your question, please click Mark As Answer on that post. If you find a post helpful, please click Vote as Helpful.
    Monday, November 4, 2013 10:28 PM
  • I noticed that the above problem occurs only launching the application via Visual Studio. However, if I manually launch the executable file, the above problem does not occur. What could be the reason for this behavior?
    • Edited by archimede83 Tuesday, December 17, 2013 12:40 AM
    Tuesday, December 17, 2013 12:39 AM