Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

c# - what's the proper way to use a ThreadPool?

If my understanding of the way the ThreadPool works is correct, one of its purposes is to limit the number of worker threads within a process that can be created at a given time. For example, if you set MaxThreads to 5 and then call QueueUserWorkItem 30 times, 30 requests will be made to the ThreadPool, but only 5 of those requests will be serviced by a new thread, while the other 25 requests will be added to the queue and serviced one at time as previous requests complete and existing threads becomes available.

In the code below, however, the call to Thread.Sleep(-1) guarantees that the DoSomething() method will never return, meaning that the current thread will never become available to subsequent requests.

But my understanding of the way a ThreadPool works cannot be correct, because if it were correct the code below would print only the numbers 0-4, rather than 0-29.

Can someone please explain how the ThreadPool works and why the below code isn't doing what I thought it should be doing?

    static void DoSomething(object n)
    {
        Console.WriteLine(n);
        Thread.Sleep(-1);
    }

    static void Main(string[] args)
    {
        ThreadPool.SetMaxThreads(5, 5);
        for (int x = 0; x < 30; x++)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomething), x);
        }
        Console.Read();
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ThreadPool.SetMaxThreads(5, 5)

means the number of active thread is 5 (if you have more than 5 cpu core), does not mean that the ThreadPool can only create 5 threads. The ThreadPool maximum number of threads = CPU Core * 250.

After Thread.Sleep, the thread is inactive, so it will not affect the execution of other threads.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...