Question

Good day.

I really need help on this issue. I have tried every possible option here.

I use a REST API in an Outlook add-in using C#. The code links outlook items to CRM records, one way. The add-in works 100% fine but after a couple of calls outs i keep on getting the error "The operation has timed out".

When I use the Google Chrome App "Advanced REST Client" I can post the same request 50 times after each other with no time out error.

From within the add-in I use POST, GET and PATCH HttpWebRequest and I get the error for all of them. The error happens at the code line System.IO.Stream os = req.GetRequestStream();

Below is the method:

public static string HttpPatch(string URI, string Parameters) 
{

var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URI);

    if (GlobalSettings.useproxy.Equals("true"))
    {
        req.Proxy = WebRequest.DefaultWebProxy;
        req.Credentials = new NetworkCredential(GlobalSettings.proxyusername,          GlobalSettings.proxypassword, GlobalSettings.proxydomain);
        req.Proxy.Credentials = new NetworkCredential(GlobalSettings.proxyusername,     GlobalSettings.proxypassword, GlobalSettings.proxydomain);
    }


req.Headers.Add("Authorization: OAuth " + GlobalSettings.token.access_token);
req.ContentType = "application/json";
req.Method = "PATCH";
byte[] data = System.Text.Encoding.Unicode.GetBytes(Parameters);
req.ContentLength = data.Length;
using (System.IO.Stream os = req.GetRequestStream())
{
    os.Write(data, 0, data.Length);
    os.Close();
}

WebResponse resp;

try
{
    resp = req.GetResponse();
}
catch (WebException ex)
{

    if (ex.Message.Contains("401"))
    {
    }
}
}
Was it helpful?

Solution

I suspect the problem is that you're not disposing of the WebResponse. That means the connection pool thinks that the connection is still in use, and will wait for the response to be disposed before reusing it for another request. The connection is needed in order to get a request stream, and it won't become available unless the finalizer happens to kick in at a useful time, hence the timeout.

Simply change your code using the response to use a using statement - or in your case, potentially something a little more complicated using a finally block as you're assigning it within a try block. (We can't really see how you're using the response, which makes it hard to give sample code around that. But fundamentally, you need to dispose it.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top