Question

I'm calling a third party web API to update some of our data on their side. I've been submitting about five jobs in quick succession and, without fail, the first two requests are working properly. The last three however never update. The application seems to be indicating that the request is timing out, but I want to make sure that I'm not messing anything up on my side.

I'm calling the function below with an Action<string, Dictionary<string,object>> Delegate and I'm using BeginInvoke to call the API asynchronously. I don't really care about the response. Am I misunderstanding something about WebRequest.GetResponse() or is this a problem with the endpoint?

    private void UpdateJobInfo(string jobId, Dictionary<string, object> updates)
    {
        var postData = GetJsonEncodedValues(updates);
        var request = WebRequest.Create(string.Format(JobResultEndpoint, _username, jobId));

        request.ContentType = "application/json; charset=utf-8";
        request.Method = WebRequestMethods.Http.Put;
        request.Headers[HttpRequestHeader.Authorization] = GetAuthenticationCredentials();
        request.GetRequestStream().Write(Encoding.ASCII.GetBytes(postData), 0, Encoding.ASCII.GetBytes(postData).Length);

        request.GetResponse();
    }
Was it helpful?

Solution

You're not disposing of the response (or indeed the request stream, although that's a slightly different matter). That means you're leaving the connection to the server open until the finalizer happens to notice that the response can be finalized. The connections are pooled with (by default) two connections per URL. So your later requests are waiting for the earlier responses to be finalized before they can obtain a connection.

Better code:

// Is this definitely what you want? What about non-ASCII data?
byte[] binaryPostData = Encoding.ASCII.GetBytes(postData);
using (var requestStream = request.GetRequestStream())
{
    requestStream.Write(binaryPostData, 0, binaryPostData.Length);
}

using (var response = request.GetResponse())
{
    // We don't care about the response, but we have to fetch it
    // and dispose it.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top