Search code examples
c#threadpoolblock

C# ThreadPool one thread blocks other?


I have a C# console app where I have a threadpool. In the threadpool there will be a class thats executes a continuous method (till it has ran for a certain period of time or when it knows when to stop). The method connects to an HttpWebResponse stream and keep reeding it.

The problem is that for a short time all threads just do their things but then only one threads keep showing it's output and the rest is waiting for that thread.

This is the method that is executed for each thread.

function void ReadStream()
        byte[] buf = new byte[8192];

        String domain = streamingUrl

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(domain);
        HttpWebResponse response = (HttpWebResponse)
        request.GetResponse();

        Stream resStream = response.GetResponseStream();

        string tempString = null;
        int count;
        do
        {
            // fill the buffer with data
            count = resStream.Read(buf, 0, buf.Length);

            if (count != 0)
            {
                tempString = Encoding.ASCII.GetString(buf, 0, count);

                try
                {
                    mySqlManager.SaveResult(tempString);

                    Console.WriteLine("Been here");
                    Thread.Sleep(1000);
                }
                catch (Exception e)
                {
                }
            }
        }
        while (count > 0);
    }

Solution

  • Firstly, you should wrap both response and resStream in using blocks to ensure they are disposed of properly.

    Second, putting long-running threads in the ThreadPool is not really the best idea, in my opinion. The idea of the ThreadPool class is that it allows you to queue up relatively small actions where spawning a new thread for each one would be wasteful. If you have operations that will take a significant amount of time to run, I would advise actually creating dedicated Thread objects for each.