GetRequestStream抛出超时异常

时间:2015-02-19 15:39:23

标签: c# .net multithreading

我有多线程核心C#app,它使用外部lib(也用C#编写)与webservice进行交互。同步模式中的多个线程中的核心应用程序从lib调用方法。 在负载比平时更高的情况下,此方法执行最多20-40秒甚至更多秒,并且有时抛出超时异常。这里代码和标记行,抛出异常

public static class NetCommunicator
{
    static string MakeHttp(string url, string body)
    {
        WebRequest r = WebRequest.Create(url);

        r.Method = body == null ? "GET" : "POST";
        r.Timeout = 60000;

        if (body != null)
        {
            r.ContentType = "text/xml; charset=utf-8";
            byte[] bytes = Encoding.UTF8.GetBytes(body);
            using (Stream s = r.GetRequestStream()) // this line execute up to 20-40 and more sec, and sometimes throw timed out exception
                s.Write(bytes, 0, bytes.Length);
        }

        using (WebResponse httpResp = r.GetResponse())
        using (Stream s = httpResp.GetResponseStream())
        using (StreamReader sr = new StreamReader(s))
            return sr.ReadToEnd();
    }

    public static string MakeHttpPost(string url, string body)
    {
        return MakeHttp(url, body);
    }
}

0 个答案:

没有答案