TheJediCowboy
TheJediCowboy

Reputation: 9222

C# HTTP Post code causing Worker Process Hang Up

We have been noticing hanging requests when viewing worker processes in IIS, and we initially thought that specifying an HTTP timeout value would solve the problem, but it didn't. We located the piece of code causing the issue, but we are still unsure what might be causing it.

The following piece of code takes in a List of Key/Value pairs and creates a HTTP Post request and puts the values in the POST payload. It works most of the time fine, but not sure what might be causing the problems.

    public List<KeyValuePair<string, string>> Data { get; set; }

    public string Invoke()
    {
        StringBuilder paramBuilder = new StringBuilder();

        for (int i = 0; i < Data.Count; i++)
        {
            var d = Data[i];
            string delimeter = i < Data.Count - 1 ? "&" : string.Empty;
            paramBuilder.AppendFormat("{0}={1}{2}", d.Key.Trim(), d.Value != null ? HttpUtility.UrlEncode(d.Value.Trim()) : string.Empty, delimeter);
        }

        WebRequest request = WebRequest.Create(Url);
        request.ContentLength = paramBuilder.Length;
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";

        Stream rs = request.GetRequestStream();
        ASCIIEncoding encoding = new ASCIIEncoding();
        var postData = encoding.GetBytes(paramBuilder.ToString());
        rs.Write(postData, 0, postData.Length);

        var response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string str = reader.ReadToEnd();

        rs.Close();     //JUST ADDED _ MAYBE THESE WERE THE PROBLEM?
        reader.Close(); //JUST ADDED - MAYBE THESE WERE THE PROBLEM?

        return str;
    }

Any ideas would be helpful.

Thanks

Upvotes: 1

Views: 204

Answers (1)

nimeshjm
nimeshjm

Reputation: 1708

You are possibly running out of resources. Whenever you create an instance of an object that implements IDisposable, you should wrap it in a "using" statement or in a try/finally block. Failing to do so will cause you application to hang until the resources are released.

This will ensure that the resources are properly managed and released when you leave the scope of the method.

http://msdn.microsoft.com/en-gb/library/yh598w02(v=vs.100).aspx

In your case, you should wrap Stream rs = request.GetRequestStream(); and StreamReader reader = new StreamReader(response.GetResponseStream()); so that you don't leak resources.

Also, wrap your code in try/catch blocks and log the exceptions so you can analyze the errors.

Upvotes: 1

Related Questions