what's the proper way to use a ThreadPool? what's the proper way to use a ThreadPool? multithreading multithreading

what's the proper way to use a ThreadPool?


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.


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

Yes your assumption is very much correct.

Since u have queued 30 jobs in a ThreadPool and the Jobs will sleep for InfiniteTime, they will never finish, the ThreadPool class will wait for a certain interval to create new thread, but will not exceed the max number of threads.

NOTE

Console.Read() is keeping your Background thread alive.

Articles

From MSDN

Many applications create threads that spend a great deal of time inthe sleeping state, waiting for an event to occur. Other threads mightenter a sleeping state only to be awakened periodically to poll for achange or update status information. Thread pooling enables you to usethreads more efficiently by providing your application with a pool ofworker threads that are managed by the system. One thread monitors thestatus of several wait operations queued to the thread pool. When await operation completes, a worker thread from the thread poolexecutes the corresponding callback function.


When all thread pool threads have been assigned to tasks, the threadpool does not immediately begin creating new idle threads. To avoidunnecessarily allocating stack space for threads, it creates new idlethreads at intervals. The interval is currently half a second,although it could change in future versions of the .NET Framework.


The threads in the managed thread pool are background threads. Thatis, their IsBackground properties are true. This means that aThreadPool thread will not keep an application running after allforeground threads have exited.


It may be that the Thread.Sleep(-1) is not doing what you expect.

Parameter Int32: The number of milliseconds for which the thread is blocked. Specify zero (0) to indicate that this thread should be suspended to allow other waiting threads to execute. Specify Infinite to block the thread indefinitely.

http://msdn.microsoft.com/en-us/library/d00bd51t.aspx

You should look into Tasks, http://msdn.microsoft.com/en-us/library/dd235608.aspx Think of it as Threadpool 2.0