Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

c# - GetRequestStream throws Timeout exception randomly

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

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

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();

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...