ThreadPool performs asynchronous operations and threadpool performs asynchronous operations
Use ThreadPool _ class to execute asynchronous tasks
/* The ThreadPool class is a static type class. When the ThreadPool class is used for asynchronous execution, the ThreadPool QueueUserWorkItem method is often called. This method has an overloaded version, as shown below: public static bool QueueUserWorkItem (WaitCallback callBack); public static bool QueueUserWorkItem (WaitCallback callBack, object state ); the QueueUserWorkItem method accepts a WaitCallback-type delegate as the callback method and can select the Data Object required to pass a thread pool thread to execute the callback method. The WaitCallback delegate type is defined as follows: public delegate void WaitCallback (object state); The QueueUserWorkItem method of the thread pool will be returned immediately after the call, and the passed callback method will be executed by the thread pool thread later. The code for executing an asynchronous task using a thread pool thread is as follows :*/
Example:
Namespace uses ThreadPool _ class to execute asynchronous tasks {class Program {static void Main (string [] args) {Console. writeLine ("the main Thread starts executing the task, Thread ID: {0}", Thread. currentThread. managedThreadId); // use ThreadPool. the QueueUserWorkItem method adds an asynchronous task to the thread pool task queue, // a data object can be passed when the thread pool thread executes the method // if no data is required to be passed, uk maliciously uses QueueUserWorkerItem and only WaitCallback a version of the parameter type // or null ThreadPool is passed. queueUserWorkItem (state => {Console. writeLine ("Thread Pool thread starts to execute asynchronous tasks. Thread ID: {0} ", Thread. currentThread. managedThreadId); for (int I = 0; I <10; I ++) {Console. writeLine (I) ;}}, null); Console. writeLine ("the main thread executes other tasks. Thread ID: {0} ", Thread. currentThread. managedThreadId); // sets the call Thread to sleep for 2000 milliseconds, waiting for the Thread pool to be executed completely. sleep (1, 2000); Console. writeLine ("the main thread continues to execute the task. Thread ID: {0} ", Thread. CurrentThread. ManagedThreadId );}}}
Thread Pool Management
/* CLR allows developers to set the maximum and minimum worker threads and IO threads to be created in the thread pool, but it is best not to set the number of threads in the thread pool, CLR sets a default value of 1000 for the maximum number of worker threads and I/O threads in the thread pool. We can use the following method of thread pool to set the number of thread pools and obtain the difference between the maximum number of thread pools and the number of currently running threads ** // set a thread that can be simultaneously active the number of requests in the pool. // All requests larger than this value will be queued until the thread pool thread becomes available. Public static bool SetMaxThreads (int workerThreads, int completionPortThreads); // when a new request is sent, set the minimum number of threads to be created on demand in the thread pool before switching to the management thread creation and destruction algorithms. Public static bool SetMinThreads (int workerThreads, int completionPortThreads); // retrieves the number of thread pool requests that can be simultaneously active. All requests larger than this value will be queued until the thread pool thread becomes available. Public static void GetMaxThreads (out int workerThreads, out int completionPortThreads); // when a new request is sent, retrieve the minimum number of threads created on demand in the thread pool before switching to the management thread creation and destruction algorithms. Public static void GetMinThreads (out int workerThreads, out int completionPortThreads); // gets the difference between the maximum number of threads in the thread pool and the current number of running threads. Public static void GetAvailableThreads (out int workerThreads, out int completionPortThreads );*/
Sample Code:
Manage threads in the namespace thread pool {class Program {static void Main (string [] args) {int worker, io; // obtain the default maximum number of threads in the thread pool. ThreadPool. getMaxThreads (out worker, out io); Console. writeLine ("1, CLR thread pool default maximum thread data, worker thread count: {0}, IO thread count: {1}", worker, io ); // set the maximum number of threads in the thread pool ThreadPool. setMaxThreads (100,100); ThreadPool. queueUserWorkItem (state => {Thread. sleep (1, 2000); Console. writeLine ("4, thread pool thread starts to execute asynchronous tasks. Thread ID: {0}, ", Thread. currentThread. managedThreadId) ;}); Console. writeLine ("2. After the default maximum thread data of the custom thread pool is set, the number of worker threads: {0}, and the number of IO threads: {1}:", worker, io ); // obtain the difference ThreadPool between the maximum number of threads in the thread pool and the current number of running threads. getAvailableThreads (out worker, out io); Console. writeLine ("3, get the difference between the maximum thread pool thread count and the current number of running threads, worker thread: {0}, IO thread: {1}", worker, io ); console. readKey ();}}}
/* The worker thread in the thread pool is the thread used by many asynchronous computing task locks. Inside the thread pool, the worker thread uses the first-in-first-out algorithm to extract work items from the whole queue of the thread and execute the task. Multiple worker threads may retrieve work items from the global queue at the same time. Therefore, all worker threads compete for a thread synchronization lock, to ensure that two or more worker threads do not retrieve work items at the same time. * ** When a thread pool creates a worker thread, the ThreadPool. setminthreads method lock value is created by default. If this value is not set, a worker thread with the same CPU count allowed by the application process will be created. This thread briefly describes the execution of the thread pool task, allows you to dynamically create more or destroy Idle threads. **/
Flow of thread execution Context
/* Each thread has an execution context. The execution context includes security settings, host settings, and logical call context data. CLR flows the execution Context Data of the initial thread to the auxiliary thread by default, when the initial thread collects and copies the execution Context Data and passes the data to the auxiliary thread, performance loss occurs. If you do not renew the preceding and subsequent execution data, you can use the system.threading.exe cutioncontext class to organize the execution of Context data flow. * Common method: ::::::::::::::::: ** // indicates whether the execution context flow has been canceled. Public static bool IsFlowSuppressed (); // restores the flow of execution context between asynchronous threads. Public static void RestoreFlow (); // cancel the flow of execution context between asynchronous threads. Public static AsyncFlowControl SuppressFlow (); */namespace thread execution context flow {class Program {static void Main (string [] args) {// stores the object in the calling logic context, and associate the object with the specified name. runtime. remoting. messaging. callContext. logicalSetData ("key", "this is the execution Context Data of the main thread"); Console. writeLine ("main thread execution Context Data: {0}", System. runtime. remoting. messaging. callContext. logicalGetData ("key"); // prevents the main thread from passing ExecutionContext for Context Data Execution. suppressFlow (); // cancel the flow of the execution context directly in the asynchronous thread Console. writeLine ("Whether the context transfer is blocked after the suppressFlow method is called: {0}", ExecutionContext. isFlowSuppressed (). toString (); ThreadPool. queueUserWorkItem (state => {Console. writeLine ("execution context data is blocked for transmission: {0}", System. runtime. remoting. messaging. callContext. logicalGetData ("key");}); // There is no output // resume the ExecutionContext of the main thread's execution context data transfer. restoreFlow (); // returns the flow Console of the execution context on the asynchronous thread. writeLine ("Whether the context transfer is blocked after the RestoreFlow method is called: {0}", ExecutionContext. isFlowSuppressed (). toString (); ThreadPool. queueUserWorkItem (state => {Console. writeLine ("the execution context data is not blocked for transmission: {0}", System. runtime. remoting. messaging. callContext. logicalGetData ("key") ;}); // queues methods for Console execution. readKey ();}}}