GetRequestStream抛出超时异常随机 [英] GetRequestStream throws Timeout exception randomly

查看:865
本文介绍了GetRequestStream抛出超时异常随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

google搜索几天后,我真的不能说明解决问题。希望在这里会找到一个解决方案。

After googling for couple of days, I really cannot solve described issue. Hope here will find a solution

我打电话同一台服务器上WCF服务时使用连接code。我随机得到超时错误呼叫WebReq.GetRequestStream()

I'm using attached code when calling WCF service on the same server. I get Timeout error randomly in call WebReq.GetRequestStream()

当我检查netstat的我看到的连接保持打开状态,因此很可能是有问题,但我不知道如何解决它。

When I'm check netstat I see that connection remains open, so probably is there a problem, but I don't know how to solve it

       //request inicialization
        HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
        WebReq.Method = "POST";
        WebReq.ContentType = "application/json; charset=utf-8";
        WebReq.ContentLength = buffer.Length;

        WebReq.Proxy = null;
        WebReq.KeepAlive = false; //also tried with true
        WebReq.AllowWriteStreamBuffering = false; //also tried with true

        //this produces an error
        using (Stream PostData = WebReq.GetRequestStream())
        {
            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();
        }

         //open and read response
         HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
         Stream Answer = WebResp.GetResponseStream();
         StreamReader _Answer = new StreamReader(Answer);

         WebResp.Close();

         //return string
         return _Answer.ReadToEnd();

超时的空闲时间约10秒后大多抛出后,还排在五年左右的请求。真的找不到一个模式。

Timeout is thrown mostly after some 10 seconds of idle time, but also after five or so requests in the row. Really cannot find a pattern.

可能是什么不对的code?是否有用于调用WCF服务的任何其他(更好)的方式?

What could be wrong with this code? Is there any other (better) way for calling WCF service?

推荐答案

我不知道它是这个问题绝对负责,但你只有在关闭网页的响应,如果它不抛出一个异常,你'再从未关闭响应流。使用使用语句:

I don't know that it's definitely responsible for the problem, but you're only closing the web response if it doesn't throw an exception, and you're never closing the response stream. Use using statements:

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream())
{
    return reader.ReadToEnd();
}

这可以很好地解释这个问题,因为如果你留下一个回应打开它会保持到Web服务器的连接开放 - 这意味着连接池则不能使用该连接

This could well explain the problem, as if you leave a response open it will keep the connection to the web server open - which means connection pooling then can't use that connection.

这篇关于GetRequestStream抛出超时异常随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆