Multithreading (3) ThreadPool and multithreading threadpool

Source: Internet
Author: User

Multithreading (3) ThreadPool and multithreading threadpool

The Thread class can be used to create and start threads. However, as more threads are enabled, manual operations are required to create and terminate threads. Another problem is that, when opening more new threads but useless threads are not terminated in time, more and more system resources will be occupied, affecting performance.

So ,. net introduces ThreadPool for us. We only need to put the task to be executed in the thread pool. The thread opening, including the release of resources, are all done by the thread pool. The following describes how to use the thread pool.

ThreadPool

Core class: System. Threading. ThreadPool. The thread pool is managed by. Net CLR. Each CLR has a thread pool instance.
Each process has a thread pool. The default thread pool size is: each available processor has 25 threads.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.
The ThreadPool type has a static method of QueueUserWorkItem. This static method receives a delegate, representing a user-defined asynchronous operation. After the modification method is called, the delegate enters the internal queue. If there is no thread in the thread pool, a new worker thread will be created and the first delegate in the queue will be put into the worker thread.
If you add new operations to the thread pool, after all the previous operations are completed, you may only need to reuse one thread to execute these new operations. If the execution frequency of QueueUserWorkItem is too high, the thread pool will create more threads to execute these new asynchronous delegates.
The number of threads in the thread pool is limited. If there are no Idle threads to execute these asynchronous delegate operations, in this case, the new asynchronous delegate operation will wait in the internal queue of the thread pool, until the middle-aged worker thread in the thread pool is idle (capable) for execution.
When you stop adding a new asynchronous delegate operation to the thread pool, the thread pool will delete unused threads that expire after certain events and release system resources that are no longer in use.

The use of the thread pool is very simple, the following code:

Namespace ConsoleApplication18 {class Program {static void Main (string [] args) {Console. writeLine ("Main thread starting... "); // 1, without the ThreadPool parameter. queueUserWorkItem (AsyncAction); Thread. sleep (TimeSpan. fromMilliseconds (3000); // 2, with the ThreadPool parameter. queueUserWorkItem (AsyncAction, "Async state"); Thread. sleep (TimeSpan. fromMilliseconds (3000); // 3, lambda expression ThreadPool. queueUserWorkItem (item => {Console. WriteLine ("Sub thread starting..."); Console. WriteLine ("Action state:" + item ?? String. empty); Console. writeLine (string. format ("Current thread id: {0}", Thread. currentThread. managedThreadId) ;}, "Lambda state"); Thread. sleep (TimeSpan. fromMilliseconds (3000); Console. writeLine ("Main thread completed! "); Console. readKey ();} /// <summary> /// delegate matching method /// </summary> /// <param name = "obj"> </param> static void AsyncAction (Object obj) {Console. writeLine ("Sub thread starting... "); Console. writeLine ("Action state:" + obj ?? String. Empty); Console. WriteLine (string. Format ("Current thread id: {0}", Thread. CurrentThread. ManagedThreadId ));}}}

 

Output result:

 

Not suitable for scenarios where thread pools are used

It is so easy to create a thread using a thread pool, and the performance is good. Will all the threads created later use the thread pool? The answer is no.

The following scenarios are not suitable for thread pools, but for creating and managing threads by yourself:

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.