开发者

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);
    }


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.


You should really break in the debugger to find out where each thread is stopped at, but my guess is that the culprit is

mySqlManager.SaveResult(tempString);

mySqlManager appears to be a class property, which means you need to be especially careful about thread safety. Make sure that SaveResult() is thread-safe; if not, then you need to make your call to SaveResult() thread-safe with locking.

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜