C # Thread Pool

Source: Internet
Author: User

Many applicationsProgramMultiple Threads are used, but these threads often spend a lot of time waiting for the event to happen in sleep state. Other threads may enter sleep state, and are only periodically awakened to change or update status information in polling mode, and then enter sleep state again. To simplify the management of these threads, the. NET Framework provides a thread pool for each process so that the application can effectively use multiple threads as needed. A thread monitors several pending operations in the thread pool. When a wait operation is completed, a secondary thread in the thread pool executes the corresponding callback function. The threads in the thread pool are managed by the system. programmers can concentrate on application tasks without having to perform thread management.

A thread pool is a form of multi-threaded processing. during processing, tasks are added to the queue, and these tasks are automatically started after the thread is created. All threads in the thread pool are backend threads. Each thread uses the default stack size, runs at the default priority, and is in a multi-threaded unit. If a thread is hostedCodeIdle (such as waiting for an event), the thread pool inserts another auxiliary thread to keep all processors busy. If all threads in the thread pool remain busy but the queue contains pending jobs, the thread pool will create another auxiliary thread after a period of time. However, the number of threads will never exceed the maximum value. Other threads that exceed the maximum value can be queued, but they will not start until other threads are completed.

The thread pool is particularly suitable for executing tasks that require multiple threads. The thread pool can optimize the execution process of these tasks to increase the throughput. It not only enables the system to optimize the execution process for this process, it also enables the system to optimize the execution process for other processes on the computer. If you need to start multiple different tasks without setting the attributes of each thread separately, you can use the thread pool.

If the application requires specific thread control, it is not suitable for using the thread pool. You need to create and manage your own threads. The thread pool is not suitable for use in the following scenarios:

-To give a task a specific priority.

-If there are tasks that may run for a long time (and thus block other tasks.

-To place threads in a single thread unit (all threads in the thread pool are in a multi-thread unit ).

-If you need to use a permanent identifier to identify and control a thread, for example, you want to use a dedicated thread to stop the thread and suspend it or discover it by name.

The system. Threading. threadpool class implements the thread pool. The threadpool class is a static class that provides a series of methods for managing the thread pool.

The threadpool. queueuserworkitem method creates a thread pool thread in the thread pool to execute the specified method (represented by the waitcallback delegate), and queues the thread into the thread pool for execution. The prototype of the queueuserworkitem method is:

Public static Boolean queueuserworkitem (waitcallback WC, object State );

Public static Boolean queueuserworkitem (waitcallback WC );

These methods arrange "work items" (and optional State data) in the thread pool and return immediately. A work item is only a method (identified by the WC parameter) that is called and passed to a single parameter, that is, status data ). The queueuserworkitem version without the status parameter passes null to the callback method. Some threads in the thread pool will call the callback method represented by the system. Threading. waitcallback delegate to process the work item. The callback method must match the system. Threading. waitcallback delegate type. Waitcallback is defined as follows:

Public Delegate void waitcallback (Object State );

The object type parameter passed in when queueuserworkitem is called is passed to the task process. You can pass parameters to the task process in this way. If the task requires multiple parameters, you can define the class containing the data and forcibly convert the instance of the class to the object data type.

Each process has only one thread pool. When a process starts, the thread pool is not automatically created. The thread pool is created only when the callback method is queued for the first time (for example, the threadpool. queueuserworkitem method is called. One thread monitors all tasks that have been queued into the thread pool. After a task is completed, the thread in the thread pool executes the corresponding callback method. You cannot cancel a work item after it is queued.

The number of threads in the thread pool is limited by the available memory. However, the thread pool enforces a limit on the number of threads that are allowed to be simultaneously active in the process (depending on the number of CPUs and other factors ). By default, each system processor can run a maximum of 25 thread pool threads. You can use the threadpool. getmaxthreads and threadpool. setmax threads methods to obtain and set the maximum number of threads in the thread pool.

Even when all threads are idle, the thread pool will maintain the minimum number of available threads so that the queue task can be started immediately. Idle threads exceeding this minimum will be terminated to save system resources. By default, each processor maintains an idle thread. The threadpool. getminthreads and threadpool. setminthreads methods can be used to obtain and set the number of Idle threads maintained by the thread pool.

The following program is used to calculate the values of the following functions:

 

// Threadpool. CS

// Thread pool example

Using system;

Using system. Threading;

Public class test

{

// Store the field of the value to be calculated

Static double number1 =-1;

Static double number2 =-1;

Public static void main ()

{

// Obtain the maximum number of threads in the thread pool and the minimum number of Idle threads maintained

Int maxthreadnum, portthreadnum;

Int minthreadnum;

Threadpool. getmaxthreads (Out maxthreadnum, out portthreadnum );

Threadpool. getminthreads (Out minthreadnum, out portthreadnum );

Console. writeline ("Maximum number of threads: {0}", maxthreadnum );

Console. writeline ("minimum number of Idle threads: {0}", minthreadnum );

// Function variable value

Int x = 15600;

// Start the first task: Calculate the power of X to the power of 8

Console. writeline ("start the first task: Calculate the power of {0. ", X );

Threadpool. queueuserworkitem (New waitcallback (taskproc1), X );

// Start the second task: Calculate the 8th power of X

Console. writeline ("start the second task: Calculate the 8th power root of {0. ", X );

Threadpool. queueuserworkitem (New waitcallback (taskproc2), X );

// Wait until both values are calculated

While (number1 =-1 | number2 =-1 );

// Print the calculation result

Console. writeline ("Y ({0}) = {1}", X, number1 + number2 );

}

// Start the first task: Calculate the power of X to the power of 8

Static void taskproc1 (Object O)

{

Number1 = math. Pow (convert. todouble (O), 8 );

}

// Start the second task: Calculate the 8th power of X

Static void taskproc2 (Object O)

{

Number2 = math. Pow (convert. todouble (O), 1.0/8.0 );

}

}

The output result of this program is:

Maximum number of threads: 25

Minimum number of Idle threads: 1

Start the first task: Calculate the power of 15600 to the power of 8.

Start the second task: Calculate the 8th power of 15600.

Y (15600) = 3.50742578894883e + 33

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.