C # ThreadPool class (thread pool)

Address: https: //www.cnblogs.com/scmail81/archive/2018/08/19/9503266.html

 

 

CLR thread pool thread will not be established immediately in the CLR is initialized, but the application you want to create a thread to run the task, only to initialize a thread pool thread.
When initialization is not thread pool thread to initialize the thread pool thread and other threads of the same, but after the completion of the task, the thread will not self-destruct, but in a suspended state to return to the thread pool. Until the application makes a request to the thread pool once again, the thread pool thread will re-activate the pending tasks.
This saves by creating a thread caused by the loss of performance, but also allows multiple tasks repeatedly reuse the same thread, thus saving a lot of overhead in the application's lifetime.

Established by the CLR thread pool thread always defaults to a background thread, priority number for the ThreadPriority.Normal.

Into CLR thread pool worker thread (workerThreads) and I / O threads (completionPortThreads) in two ways:

  • The worker thread is mainly used for internal operational management CLR objects, usually used for computationally intensive tasks.
  • I / O (Input / Output) thread information is for external interaction with the system, such as input and output, the CPU only when the task is started, the task will pass parameters to the device, the device can then start the hardware. Such as task completion time, CPU receive a notification, in general, it is a hardware interrupt signal, and the CPU continues subsequent processing. In the process, CPU is not necessary to fully participate in the process if the running threads do not hand over control of the CPU, the thread can only be in a wait state, even if the operating system the current CPU scheduler to the other thread, this time the thread occupied space is occupied, and are not CPU processing thread, thread waste of resources issues that may arise. If this is a network service program, each network connection uses a thread management, large number of threads that may arise are waiting for network communication, with the increasing network connection, thread in a wait state will do all it consumes memory resources . Consider using thread pool to solve this problem.

  Maximum thread pool usually defaults to 1000, 2000. When this large number of requests remain queued until the thread pool threads available there.

  Use CLR thread pool worker thread there are two ways:

  • By the ThreadPool.QueueUserWorkItem () method;
  • By commission;

  To note, whether through ThreadPool.QueueUserWorkItem () or commission, are calling thread pool thread.

It can be read and set the maximum number of threads CLR thread pool worker thread and I / O thread by the following two methods.

  1. ThreadPool.GetMax(out in workerThreads,out int completionPortThreads);
  2. ThreadPool.SetMax(int workerThreads,int completionPortThreads);

  To test how many threads in the thread pool is in use, you can ThreadPool.GetAvailableThreads (out in workThreads, out int conoletionPortThreads) method.

method Explanation
GetAvailableThreads The remaining number of idle threads
GetMaxThreads The most number of available threads, all this large number of requests remain queued until the thread pool threads becomes available
GetMinThreads Retrieving thread pool maintenance request in the new forecast in the number of idle threads
QueueUserWorkItem Have to start a thread pool thread (way of the queue, as being no idle threads the thread pool, then enter queuing)
SetMaxThreads The maximum number of threads in the thread pool
SetMinThreads Set a minimum number of threads in the thread pool needs to be retained

We can use the thread pool to solve most of the problems above, compared with the use of a single thread, use the thread pool has the following advantages:

1, to shorten the response time of the application. Because there is a thread in the thread pool thread allocation of tasks in a wait state (as long as no more than a thread pool maximum limit) without creating threads.

2, without having to manage and maintain the short life cycle of threads, do not assign resources when creating, releasing resources after the completion of its mission.

3, the thread pool will be optimized for the thread pool based on the current system features.

In short thread pool is to reduce the role of creating and destroying threads overhead. In there is a thread of class in .NET ThreadPool, which provides management thread pool.

ThreadPool is a static class, it does not have a constructor, to provide both functions are all static. Wherein a QueueUserWorkItem method, it has two overloads, as follows:

public static bool QueueUserWorkItem (WaitCallback callBack): a method queued for execution. This method has become available to perform the thread pool thread.

public static bool QueueUserWorkItem (WaitCallback callBack, Object state): The method queued for execution, and specifies the method comprising using the object data. This method has become available to perform the thread pool thread.

The method used QueueUserWorkItem WaitCallback parameter indicates a delegate, it declared as follows:

public delegate void WaitCallback(Object state)

If you need to pass the task information can be used WaitCallback the state parameters, similar to ParameterizedThreadStart delegate.

The following is an example ThreadPool code is as follows:

Copy the code
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;

namespace ConsoleApp1
{
    class ThreadPoolDemo
    {
        public ThreadPoolDemo()
        {
        }

        public void Work()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(CountProcess));
            ThreadPool.QueueUserWorkItem(new WaitCallback(GetEnvironmentVariables));
        }
        /// <summary>  
        /// 统计当前正在运行的系统进程信息  
        /// </summary>  
        /// <param name="state"></param>  
        private void CountProcess(object state)
        {
            Process [] = Process.GetProcesses Processes (); 
            the foreach (Process P in Processes) 
            { 
                the try 
                { 
                    Console.WriteLine ( "Process Information: Id: {0}, ProcessName : {1}, StartTime: {2}", p. ID, p.ProcessName, p.StartTime); 
                } 
                the catch (Win32Exception E) 
                { 
                    Console.WriteLine ( "the ProcessName: {0}", p.ProcessName); 
                } 
                the finally 
                { 
                } 
            } 
            Console.WriteLine ( "information acquisition process is completed. "); 
        }
        /// <Summary>   
        /// Get the current machine system variable   
        /// </ Summary>   
        /// <param name = "State"> </ param>   
        public void GetEnvironmentVariables (State Object) 
        { 
            the IDictionary System.Environment.GetEnvironmentVariables List = (); 
            the foreach (the DictionaryEntry in List Item) 
            { 
                Console.WriteLine ( "variable information system: Key = {0}, value = {}. 1", item.Key, item.Value); 
            } 
            Console.WriteLine ( "acquisition system variable information is completed.") ; 
        } 
    } 
}
Copy the code
Copy the code
using System;
using System.Threading;

namespace ConsoleApp1
{

    class Program
    {
        static void Main(string[] args)
        {
            ThreadPoolDemo tpd1 = new ThreadPoolDemo();
            tpd1.Work();
            Thread.Sleep(5000);
            Console.WriteLine("OK");
            Console.ReadLine();
        }
    }
}
Copy the code

Guess you like

Origin www.cnblogs.com/zxtceq/p/10980480.html