Search code examples
c#.netwebclientstreamreader

Can not close StreamReader (reader.Close(); blocks code)


I get continous [ non-stop ] mesages from web url:

    string webUrl = "xxxxx/status.cgi";
    WebClient client = new WebClient();
    client.Credentials = new NetworkCredential("UUU", "PPP");

    StreamReader reader = new StreamReader(client.OpenRead(webUrl), Encoding.UTF8,true);
    string line;
    int counter = 0;
    while ((line = reader.ReadLine()) != null)
    {
        if( line == "XXXXXX")
        {
           break;
        }
    }


    Console.WriteLine("Try to Close Stream Reader...");
    reader.Close();
    Console.WriteLine("Stream Reader is closed...");

The problem is that when I break from while loop, i want to close the stream reader...But stream reader does not close...."reader.Close();" hangs/block the code...

Why this happen? How to fix it?

UPDATE: "using" DOES NOT WORK IN MY CASE: Exit the loop but stream reader is not disposed...Hang/Block

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;

namespace TestStreamReader
{
    class Program
    {
        static void Main(string[] args)
        {
            string  webUrl = "http://X.Y.Z:7000/status.cgi";
            int counter = 0;

            using (WebClient client = new WebClient())
            {
                client.Credentials = new NetworkCredential("admin", "000000");

                using (StreamReader reader = new StreamReader(client.OpenRead(webUrl), Encoding.UTF8, true))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        counter++;

                        Console.WriteLine("Input"+ line);

                        if (counter == 10)
                        {
                            Console.WriteLine("I am exiting the loop");
                            break;
                        }


                    }

                    Console.WriteLine("Exit the while loop");

                }

                Console.WriteLine("Reader should be desposed");
            }

            Console.WriteLine("Web Client should be disposed!");



        }
    }
}

Solution

  • Instead of using WebClient, have you thought about using HttpWebRequest and getting the response stream?

    //using System.Net;
    
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ApiProcedure.FunctionUri);
        request.Credentials = (CredentialCache)Credentials;
        request.PreAuthenticate = true;
    
        //define the type of request
        request.Method = HttpMethod;
        request.ContentType = "application/json";
    
        //execute
        StreamReader sr = new StreamReader(response.GetResponseStream());
        return sr.ReadToEnd();
    

    I know you're doing a continuous stream, but you should be able to treat the stream reader normally like you're doing in your example. I think this method will give you a little more control.

    I normally only use WebClient if I need to perform a simple task where all the nitty gritty setup/streams are done for me. Find I get better results when managing the request and response separately.

    Good luck!

    EDIT: Also, this is just a snippet from my code. You might want to take a look here: C# - How to read a continuous stream of XML over HTTP for a good example of reading continuous chunks of data.