ThreadPool (thread pool) in. Net

Source: Internet
Author: User

This article from: http://rickie.cnblogs.com/archive/2004/11/23/67275.html

In multi-threaded programs, there are often two situations. In one case, the thread in the application spends most of its time waiting for an event to occur before it can respond, while the other is that the thread is normally dormant and is only periodically woken up. The ThreadPool class in the. Net framework is analyzed and introduced here to deal with the first case, and the QueueUserWorkItem method and the WaitCallback delegate are also discussed accordingly. Instead of using a Timer (System.Threading.Timer or System.Windows.Forms.Timer) to deal with the second case, you can refer to the The TimerCallback delegate of the System.Threading.Timer class .

1. ThreadPool Introduction (fromMSDN)

The ThreadPool class provides a thread pool that can be used to send work items, handle asynchronous I/O, wait on behalf of other threads, and handle timers. The thread pool allows multiple jobs to be run in the background without the need to create and destroy separate threads frequently for each task, thus reducing overhead.

The thread pool enables you to use threads more efficiently by providing the application with a pool of worker threads that are managed by the system. A thread monitors the status of several wait operations that are queued to the thread pool. When a wait operation completes, a worker thread in the thread pool executes the corresponding callback function.

You can also arrange work items that are not related to the wait operation to the thread pool. To request that a work item be processed by a thread in the thread pool, call the QueueUserWorkItem method. This method will use a reference to a method or delegate that will be invoked from a selected thread in the thread pool as a parameter. Once a work item is queued, it cannot be canceled.

Timers in the timer (System.Threading.Timer) queue and registered wait operations also use the thread pool. Their callback functions are also arranged into the thread pool. For the contents of this section, we can refer to theTimerCallback Commission of System.Threading.Timer class .

The thread pool is created the first time an instance of the ThreadPool class is created. The thread pool has a default limit of 25 threads per available processor, which can be changed using the corsetmaxthreads defined in the Mscoree.h file. Each thread uses the default stack size and runs at the default priority level. Each process can have only one operating system thread pool.

2. ThreadPool.QueueUserWorkItem Method

The QueueUserWorkItem method queues the specified method into the queue for execution and specifies the object that contains the data used by the method, which executes when the thread pool threads become available.

public static bool QueueUserWorkItem (

WaitCallback CallBack,

Object state

);

True if the method is queued successfully; False otherwise. If the queued method requires only a single data item, you can cast the data item to type Object. If the method requires more complex data, you must define the class that contains the data. If no arguments are passed in, you can call the QueueUserWorkItem (WaitCallback callBack) overload.

The public methods provided by ThreadPool are static methods, so there is no need to generate ThreadPool objects. After adding a work item to the thread pool through the QueueUserWorkItem method, there is currently no simple method to cancel. You do not need to establish a consultative thread, just rely on the corresponding function or method relying on the WaitCallback delegate to the ThreadPool.QueueUserWorkItem () method. and the creation, management and operation of threads are automatically completed by the system, which is the advantage of ThreadPool.

3. WaitCallback Commission

The WaitCallback delegate declares the callback method to be executed by the thread pool, and the declaration of the callback method must have the same parameters as the WaitCallback delegate declaration.

WaitCallback represents the callback method to execute on the ThreadPool thread. Create a delegate by passing the callback method to the WaitCallback constructor. Your method must have the signature shown here. The task is queued for execution by passing the WaitCallback delegate to ThreadPool.QueueUserWorkItem. Your callback method will be executed when a thread pool threads are available.

If you want to pass information to the callback method, create an object that contains the information you want and pass it to QueueUserWorkItem when the task is queued for execution. Each time you execute your callback method, the state parameter contains this object.

The task is queued in the thread pool by packaging a method into the WaitCallback delegate and then passing the delegate to the ThreadPool.QueueUserWorkItem static method.

4. Demo Application using ThreadPool class

There's a good demo on codeproject.com: Proper Threading in Winforms. Net, written by Shawn Cicoria, with Source code.

In the demo program above, not only the method of using the ThreadPool thread pool is provided, but also the methods of thread and ThreadStart delegate are demonstrated.

private void Button1_Click (object sender, System.EventArgs e)

{

ShowProgressDelegate showprogress = new ShowProgressDelegate (showprogress);

int imsgs = 100;

One-to-one ... Using ThreadPool

if (cbthreadpool.checked)

{

Object obj = new object[] {This, showprogress, imsgs};

Workerclass WC = new Workerclass ();

BOOL rc = ThreadPool.QueueUserWorkItem (new WaitCallback (WC). runprocess), obj);

Enablebutton (! RC);

}

Else

{

another. Using Straight Threads

Workerclass WC = new Workerclass (this, showprogress, new object[] {imsgs});

Thread t = new Thread (new ThreadStart (WC). runprocess));

T.isbackground = true; Make them a daemon-prevent thread callback issues

T.start ();

Enablebutton (FALSE);

}

}

In addition, the BeginInvoke method of the Windows Form control is called in the demo program above: Executes the specified delegate asynchronously with the specified parameters on the thread that creates the control's underlying handle. The BeginInvoke method callbacks the specified delegate on different thread pool threads, actually initiating a background call to place a message into the message loop of Windows Form.

Public IAsyncResult BeginInvoke (Delegate, object[]);

***

Any questions on the demo application, please leave message below. I'll try to explain it. Thanks.

References:

1, MSDN, ThreadPool, QueueUserWorkItem and WaitCallback

2, Shawn Cicoria, Proper threading in Winforms. Net, http://www.codeproject.com/csharp/winformthreading.asp

Category: D. Multithreading technology

ThreadPool (thread pool) in. Net

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.