mdm20
mdm20

Reputation: 4563

Streamreader freezing on close

I have an app that reads tweets from Twitter based on keywords. Those keywords can change periodically, and when they do, I need to close and re-open the stream. I am able to open the stream no problem, but I am having an issue when I tried to close that stream. Here is some example code:

        try
        {
            response = (HttpWebResponse)request.GetResponse();
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    WriteLogMessage("Stream open - entering loop");
                    while (true)
                    {
                        if (count == 10) break;
                        count++;

                        string tweet = reader.ReadLine();
                        Console.Write(tweet);
                    }

                    WriteLogMessage("Exited loop");
                }
                /**** Program seems to freeze and never gets past this point ****/
                WriteLogMessage("Reader disposed");
            }
            WriteLogMessage("Stream disposed");
        }
        catch (Exception ex)
        {
            WriteLogMessage(ex.Message);
        }
        finally
        {
            if (response != null)
                response.Dispose();
            WriteLogMessage("Response closed");
        }

This code runs fine on my win7 (x64) machine. However, when I deploy it to either server 2008 or server 2012 (both x64), I see this freezing behavior. I am setting no parameters on the HttpWebRequest other than a header that twitter requires. Anyone have any thoughts about whats going on?

Upvotes: 1

Views: 571

Answers (1)

Jim Mischel
Jim Mischel

Reputation: 133975

I've run into this from time to time. For reasons I don't fully understand, the stream wants to stay open until it's received everything. This became such a problem for me that I'd call request.Abort before closing the stream. In your code, for example, I would write:

    WriteLogMessage("Exited loop");
    request.Abort();
}

I blogged about it some time back: http://www.informit.com/blogs/blog.aspx?uk=The-hanging-web-request

Upvotes: 2

Related Questions