ThreadPool thread pool summary, threadpool thread Summary
The ThreadPool class provides a thread pool that can be used to send work items, process asynchronous I/O, represent other threads waiting, and process timers.
The thread pool provides an auxiliary thread pool managed by the system for applications so that you can use the thread more effectively. A thread monitors several pending operations in the thread pool. When a wait operation is completed, a secondary thread in the thread pool will execute the corresponding callback function.
The threads in the managed thread pool are backend threads, that is, their IsBackground attribute isTrue. This means that after all foreground threads have exited,ThreadPoolThe thread does not keep the application running.
You can also arrange work items unrelated to the waiting operation to the thread pool. To request a thread in the thread pool to process work items, call the QueueUserWorkItem method. This method is used as a parameter for reference to the method or delegate called by the selected thread from the thread pool. Once a work item is added to the queue, it cannot be canceled.
The timer in the timer queue and the registered pending operations also use the thread pool. Their callback functions are also arranged in the thread pool.
Each process has a thread pool. The default thread pool size is 25 threads for each available processor. You can use the SetMaxThreads method to change the number of threads in the thread pool. Each thread uses the default stack size and runs according to the default priority.
Sample Code:
using System;using System.Threading;public class Example{ public static void Main() { string str = "param"; ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), str); Thread.Sleep(1000); Console.ReadKey(); } static void ThreadProc(Object stateInfo) { Console.WriteLine(stateInfo); }}
The QueueUserWorkItem method queues the specified method for execution and specifies the object containing the data used by the method.
1. Do not pass Parameters
public static bool QueueUserWorkItem(WaitCallback callBack);
2. PASS Parameters
public static bool QueueUserWorkItem(WaitCallback callBack, object state);
True if the method is successfully queued; otherwise, false. If the queue method only requires a single data item, you can forcibly convert the data item to the type Object. If the method requires multiple complex data, you must define the class containing the data.
When to useThreadPool?
ThreadPoolRole:
Another method is to arrange task items to the thread pool. However, this task item has a task item waiting for operation.
ThreadPool. RegisterWaitForSingleObject method (WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)
Register a delegate waiting for WaitHandle (arrange task items with pending operations in the thread pool), and specify a 32-bit signed integer to indicate the timeout value (in milliseconds ).
Parameters
-
WaitObject
-
Type: System. Threading. WaitHandle
The WaitHandle to register. Use WaitHandle instead of Mutex.
-
CallBack
-
Type: System. Threading. WaitOrTimerCallback
WaitOrTimerCallback delegation called when the waitObject parameter is terminated.
-
State
-
Type: System. Object
The object passed to the delegate.
-
MillisecondsTimeOutInterval
-
Type: System. Int32
Timeout in milliseconds. If the millisecondsTimeOutInterval parameter is 0 (zero), the function tests the object status and returns immediately. If millisecondsTimeOutInterval is-1, the timeout interval of the function never expires.
-
ExecuteOnlyOnce
-
Type: System. Boolean
If the value is true, the thread no longer waits on the waitObject parameter after the delegate is called. If the value is false, the timer is reset every time the wait operation is completed until the wait is canceled.
Return Value
Type: System. Threading. RegisteredWaitHandle
The RegisteredWaitHandle that encapsulates the local handle.
After RegisteredWaitHandle returned by this method is used up, call its RegisteredWaitHandle. Unregister method to release the reference to the pending handle. We recommend that you always call the RegisteredWaitHandle. Unregister method, even if you set executeOnlyOnce to true. If you call the RegisteredWaitHandle. Unregister method instead of depending on the final of the registered wait handle, garbage collection is more efficient.
The RegisterWaitForSingleObject method queues the specified Delegate to the thread pool. When one of the following conditions occurs, the auxiliary thread will execute the delegate:
The RegisterWaitForSingleObject method checks the current status of the WaitHandle of the specified object. If the object status is not terminated, this method registers a pending operation. This wait operation is executed by a thread in the thread pool. When the object state changes to terminated or the timeout interval has expired, the delegate is executed by the auxiliary thread. If the timeOutInterval parameter is not 0 (zero) and the executeOnlyOnce parameter is false, the timer is reset whenever the event receives a signal or the timeout interval expires.
Using System; using System. threading; using System. runtime. compilerServices; public class ClassForMain {private static int I = 0; public static void Main (string [] args) {// when the initial state of WaitHandle is set to a non-terminating State, then, this method registers a waiting operation AutoResetEvent argv = new AutoResetEvent (false); // sets the timeout value to 2000 milliseconds. When the timeout interval expires, the auxiliary thread will execute the thread pool to delegate the execution. registerWaitForSingleObject (argv, new WaitOrTimerCallback (workitem), null, 2000, false); // sets the WaitHandle state to the terminating State. set (); Console. read ();} public static void workitem (object O, bool signaled) {I + = 1; Console. writeLine ("Thread Pool Work Item Invoked:" + I. toString ());}}
References:
What are the advantages of Thread pool ThreadPool over Thread?
The thread pool is designed for a sudden explosion of threads. A limited number of fixed threads are used to provide a large number of operation services, reducing the time required to create and destroy threads and thus improving efficiency.
If a thread takes a very long time, there is no need to use the thread pool (not long operations, but not suitable .), Besides, you cannot control the start, suspension, and suspension of threads in the thread pool.
Restrictions on ThreadPool of Thread Pool
Provides a thread pool that can be used to execute tasks, send work items, process asynchronous I/O, wait for other threads, and process timers.