如何优化此HTTP连接?

时间:2014-07-31 14:27:28

标签: c# .net http optimization

我是C#编程的新手,我正在努力了解如何优化这段代码,这些代码总是被调用到线程中以从IP摄像头中获取图像(快照)。我正在尝试进行一些优化以加快HTTP请求,但我无法看到如何以及在何处采取行动。如果有办法得到这个结果,我可以问专家吗?谢谢。

private Image GetImage()
{

        HttpWebRequest req = null;
        Image img = null;
        HttpWebResponse res = null;

        try
        {
            req = WebRequest.Create(_httpCommand) as HttpWebRequest;
            req.Method = "GET";
            req.PreAuthenticate = true;
            req.AllowWriteStreamBuffering = true;
            req.Credentials = new NetworkCredential(_user, _pwd);
            res = req.GetResponse() as HttpWebResponse;

            using (Stream rs = res.GetResponseStream())
            {
                img = new Bitmap(rs);
            }
        }
        catch (Exception e) {
            _status = false; //<<------------------Signaling the FAILURE status! ---

            if (img != null)
                img.Dispose(); //<< for ------GC--------------

            //insert in LOG
            Log logItem = new Log(DateTime.Now, e.Message);
            AddLogItem(logItem);
        }

        return img;
}

1 个答案:

答案 0 :(得分:3)

我记得,HttpWebRequest会尝试自动确定代理设置,这需要时间。

req.Proxy = GlobalProxySelection.GetEmptyWebProxy();

告诉它不使用任何代理,因此将跳过搜索正确的设置。