Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways of speeding up WebRequests? [duplicate]

I've made an app that can access and control Onvif cameras which it does well enough. However this is my first time making any app that uses web requests like this (or at all) so I assume I'm probably using quite basic techniques. The part of code I'm curious about is this:

        Uri uri = new Uri(
            String.Format("http://" + ipAddr + "/onvif/" + "{0}", Service));

        WebRequest request = WebRequest.Create((uri));
        request.Method = "POST";

        byte[] b = Encoding.ASCII.GetBytes(PostData);
        request.ContentLength = b.Length;
        //request.Timeout = 1000;
        Stream stream = request.GetRequestStream();
        //Send Message
        XmlDocument recData = new XmlDocument();
        try
        {
            using (stream = request.GetRequestStream())
            {
                stream.Write(b, 0, b.Length);
            }
            //Store response
            var response = (HttpWebResponse) request.GetResponse();
            if (response.GetResponseStream() != null)
            {
                string responsestring = new
                  StreamReader(response.GetResponseStream())
                  .ReadToEnd();
                recData.LoadXml(responsestring);
            }
        }
        catch (SystemException e)
        {
            MessageBox.Show(e.Message);
        }
        return recData;
    }

The code works fine, however using the writeline statements I've found that the first request takes about 400ms to complete whereas the subsequent ones only take between 10 - 20ms. Is there anything I can do to speed up the first request?

like image 945
Brandon Robson Avatar asked Jan 28 '16 13:01

Brandon Robson


1 Answers

You're doing it just fine. The reason for the difference in time to complete may be due to HTTP Keep-Alive. By default, the same connection is reused for subsequent requests. So the first request has to establish the connection, which is probably why it takes longer. The rest of the requests use the same already-open connection.

like image 150
Gabriel Luci Avatar answered Oct 13 '22 07:10

Gabriel Luci