C # Threading Knowledge-using ThreadPool to perform asynchronous operations

Source: Internet
Author: User

C # Threading Knowledge-using ThreadPool to perform asynchronous operations

There are many complex tasks in your application that may require collaboration with one or more worker threads or I/O threads, such as timed tasks, database data operations, Web services, file processing, and so on. These tasks can be time consuming, and in order for the user interface to respond in a timely manner, an additional thread is enabled to process the task in parallel. Thread creation and destruction operations are very expensive, excessive threads can incur memory resource consumption, and the operating system dispatches executable threads and performs context switches that result in time consumption, so multithreading can damage the performance of your application. The CLR uses a thread pool to manage threads if the created line Cheng Nen is used repeatedly to solve some of the above problems.

1. Thread Pool Basics

Each CLR has a thread pool, which is shared by the CLR-controlled AppDomain. Inside the online pool, which maintains an operation request queue itself, when an application needs to perform a task, it needs to call a method of the thread pool (usually the QueueUserWorkItem method) to add the task to the thread pooling work item, and the thread pool assigns the task to one of the thread pooling threads. If there are no threads in the thread pool, a thread is created to handle this task. When the task executes, the line routines back to the thread pool in an idle state, waiting for the next task to execute. Because threads are not destroyed, using thread pool threads can perform tasks more quickly.

If too many tasks in the thread pool exceed the processing power of an existing thread, the thread pooling creates more threads as needed. Because each thread consumes a certain amount of memory resources, when the thread pool is idle (the thread that does not perform the task for a long time) is too large, the threads in the threading pools automatically wake up to destroy the extra idle threads to reduce the use of resources.

Inside the online pool, all threads are background threads and the scheduling priority is normal (Threadpriority.normal), which is divided into worker or I/O threads, which are worker threads when the thread pool threads perform a complex computational task. I/O threads are used if the tasks performed are related to I/O.

2. Using the ThreadPool class to perform asynchronous tasks

The ThreadPool class is a static type class that, when executed asynchronously using the ThreadPool class, typically calls the QueueUserWorkItem method of ThreadPool, which has an overloaded version, as follows:

BOOL QueueUserWorkItem (WaitCallback callBack);          object state);

The QueueUserWorkItem method takes a delegate of the WaitCallback type as a callback method and the data object that is required to pass a callback method to the thread pool threads.

The WaitCallback delegate type is defined as follows:

void WaitCallback (object state);
The thread pool's QueueUserWorkItem method returns immediately after the call, and the callback method passed will be executed by the thread pool threads later. Execute the asynchronous task code with thread pool threads as follows:
   1:    void Main (string[] args) 
   2:          {
   3:              Console.WriteLine ("The main thread begins to perform the task. Thread id:{0} ", Thread.CurrentThread.ManagedThreadId);
   4:  
   5:              //Use the ThreadPool.QueueUserWorkItem method to add an asynchronous task to the thread pool task queue,
   6:              //Can pass a data object when a method is executed for thread pool threads.
   7:              //If you do not need to pass data you can use QueueUserWorkItem only waitcallback version of a parameter type,
   8:              //or pass NULL
   9:              ThreadPool.QueueUserWorkItem (state = {
  Ten:                  Console.WriteLine ("thread pool threads begin to perform asynchronous tasks.") Thread id:{0} ", Thread.CurrentThread.ManagedThreadId);
  One: For                  (int i = 0; i <; i++) 
  :                  {
  :                      Console.WriteLine (i);
  :                  }
  15:               
  :              },null);
  :  
  :              Console.WriteLine ("The main thread performs other tasks. Thread id:{0} ", Thread.CurrentThread.ManagedThreadId);
  A:              //causes the calling thread to sleep for 2000 milliseconds, waiting for thread pool threads to finish executing. 
  :              Thread.Sleep (2000);
  £ º  
  :              Console.WriteLine ("The main thread continues to perform the task. Thread id:{0} ", Thread.CurrentThread.ManagedThreadId);
  :          }

Program Run Results

3. Thread pool management of threads

The CLR allows the developer to set the maximum and minimum worker threads and I/O threads that the thread pool needs to create, but it is best not to set the number of threads for thread pools, the CLR sets a default value of 1000 for the worker thread of the thread pool and the maximum number of threads for I/O threads. We can use the thread pool to set and get the number of thread pool threads and get the difference between the maximum number of thread pool threads and the number of threads that are currently running:

Sets the number of requests for a thread pool that can be active at the same time.All requests that are greater than this number remain queued until the thread pool threads become available.PublicStaticBOOL SetMaxThreads (int WorkerThreads,int completionportthreads);//when a new request is made, set the minimum number of threads that the thread pool creates on demand before switching to an algorithm that manages thread creation and destruction. public static bool setminthreads (int WorkerThreads, int completionportthreads); //retrieves the number of thread pool requests that can be active at the same time. All requests that are greater than this number remain queued until the thread pool threads become available. public static void getmaxthreads (out Span class= "KWRD" >int workerthreads, out int completionportthreads); //when a new request is made, retrieves the minimum number of threads that the thread pool creates on demand before switching to an algorithm that manages thread creation and destruction. public static void getminthreads (out Span class= "KWRD" >int workerthreads, out int completionportthreads);    
Gets the difference between the maximum number of thread pool threads and the number of threads currently running.   void getavailablethreads (int completionportthreads); 
Example code:
   1:    void Setthreadnumber () {
   2:              int worker, IO;
   3:              //Get thread pool default maximum number of threads
   4:              threadpool.getmaxthreads (outworker, outio); 
   5:              Console.WriteLine ("1, CLR thread pool default max thread data, worker thread count: {0},io threads: {1}", Worker,io);
   6:              //Set thread pool maximum thread count
   7:              threadpool.setmaxthreads (100,100);
   8:              ThreadPool.QueueUserWorkItem (state =
   9:              {
  Ten:                  Thread.Sleep (2000);
  One:                  Console.WriteLine ("4, thread pool threads begin to perform asynchronous tasks. Thread id:{0} ", Thread.CurrentThread.ManagedThreadId);
  12:              
  :              });
                Console.WriteLine ("2, custom set thread pool default max thread data, worker thread count: {0},io threads: {1}", worker, IO);
  :              //Gets the difference between the maximum thread pool threads and the number of threads currently running. 
  :              threadpool.getavailablethreads (outworker, outio); 
                Console.WriteLine ("3", get the difference between the maximum thread pool threads and the number of threads currently running, worker thread: {0},io thread: {1} ", Worker,io);
  :              Console.read ();
  :          }

Execution Result:

the worker thread of the thread pool is the thread used by many asynchronous compute tasks, inside the online pool, where worker threads take a first-in, first-out algorithm to remove work items from the thread's global queue and perform tasks. There may be multiple worker threads fetching work items from the global queue at the same time, so all worker threads compete for a thread synchronization lock to ensure that two or more worker threads do not remove work items at the same time. Thread pool worker threading data structures such as:

Thread worker thread data structure diagram

The thread pool creates the value of the Threadpool.setminthreads method lock setting by default when the worker thread is created. If this value is not set, a worker thread is created that is the same number of CPUs allowed by the application process, which monitors the execution of thread pool tasks and dynamically creates more or destroys idle threads.

4. The flow of the thread execution context

Each thread has an execution context that includes security settings, host settings, and logical call context data, and the CLR defaults to flow the execution context data from the initial thread to the worker thread. The initial thread loses performance when it collects and replicates execution context data and passes it to the worker thread. If you do not need these execution context data, you can use the System.Threading.ExecutionContext class to block the flow of context data. Common methods are as follows:

             indicates whether the flow of the execution context is currently canceled.          bool isflowsuppressed ();        static AsyncFlowControl Suppressflow (); 
To execute the context flow Control Sample code:
   1:   void Execcontext () {
   2:              //Store objects in the invocation logic context
   3:              System.Runtime.Remoting.Messaging.CallContext.LogicalSetData ("Key","This is the execution context data of the main thread"); 
   4:              Console.WriteLine ("Main thread execution context data: {0}", System.Runtime.Remoting.Messaging.CallContext.LogicalGetData ( "Key")); 
   5:              //prevents the main thread from executing the delivery of context data
   6:              Executioncontext.suppressflow ();
   7:              Console.WriteLine ("Call the Suppressflow method after the context pass flow is blocked: {0}", executioncontext.isflowsuppressed (). ToString ());
   8:  
   9:              ThreadPool.QueueUserWorkItem (state = {
  Ten:                  Console.WriteLine (
  One:                      System.Runtime.Remoting.Messaging.CallContext.LogicalGetData ("Key"));
  :              });
  13:             
  :              //restore the main thread execution context data delivery
  :              Executioncontext.restoreflow ();
  0:              Console.WriteLine ("Call the Restoreflow method after the context pass flow is blocked: {}", executioncontext.isflowsuppressed (). ToString ());
  :  
  :              ThreadPool.QueueUserWorkItem (state =
  :              {
  :                  Console.WriteLine ("Execution context data is not blocked for delivery: {0}",
  £                      System.Runtime.Remoting.Messaging.CallContext.LogicalGetData ("Key"));
  :              });
  At:              Console.read ();
  :          }
Execution Result:

This article provides a brief introduction to the basic and use of the CLR thread pool and the management of threads by the threading pool, which is a good technique for performing these processes if you need to build scalable, high-performance, high-concurrency applications.

C # Threading Knowledge-using ThreadPool to perform asynchronous operations

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.