开发者

Is there a limit on how many worker items you can queue in the threadpool?

开发者 https://www.devze.com 2023-03-03 20:15 出处:网络
Is there some limit on how many items you can put in the threadpool queue? ThreadPool.QueueUserWorkItem(someCallBack);

Is there some limit on how many items you can put in the threadpool queue?

 ThreadPool.QueueUserWorkItem(someCallBack);

MSDN doesn't give any indication what the limit is, and what happens if you might pass it (does it temporarily stop the thread which is posting? or does it throw an exception?)

To give an example. What if I j开发者_Go百科ust queue 100,000 items in the queue. Will that work?


There is no theoretical limit to the number of queued items, it should keep adding callbacks to the queue until you've exhausted your resources.

But, why would you want to add that many in the first place? If you have that many items to add they're more than likely very short-lived and you'd be better off figuring out a better partitioning scheme for your task at hand.


You can use the Threadpool.GetMaxThreads() and Threadpool.SetMaxThreads() to determine/modify the maximum number of threads in the pool.

When you queue a work item it will begin execution with a free thread from the pool if possible or if all threads are busy it will wait until a thread becomes available before starting execution. You will not get an error if you queue something and there are no free threads available.


I believe the only limit is that a maximum of UInt32.MaxValue can be in the queue. If you use the 32 bit CLR you would run out of memory long beforehand, so you can never hit that limit.

I guess on the 64bit CLR you could theoretically hit that limit but I think you'd need about 850GB of memory to test it. I got up to about 40,000,000 queued items using 6-7GB of working set before starting to run out of memory (on a machine that has 8GB RAM installed).

I don't know what would happen if you hit the limit. From a quick look at mscorlib with reflector, it may not even throw an exception, but simply overflow with unpredictable results.

If you have a machine with about 1TB of memory, here's a little test snippet to try and see for yourself what happens :)

class Program
    {
        static void Main(string[] args)
        {
            for (long i = 0; ; ++i)
            {
                bool succeeded = ThreadPool.QueueUserWorkItem(SleepCallBack);
                if ((i % 1000) == 0)
                {
                    Console.WriteLine(i);
                }
                if (!succeeded) break;
            }
            Console.Read();
        }

        private static void SleepCallBack(object stateInfo)
        {
            Thread.Sleep(System.Threading.Timeout.Infinite);
        }
0

精彩评论

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

关注公众号