In multithreaded programs, there are often two scenarios:
One situation:
In an application, a thread spends most of its time waiting, waiting for an event to occur before responding
This is generally used ThreadPool (thread pool) to solve;
In another case: the line Cheng Ping is dormant and is periodically awakened
This is generally used timer (timer) to solve;
The ThreadPool class provides a system-maintained thread pool (a container that can be thought of as a thread) that requires more than Windows 2000 system support because some of these methods call API functions that are only available from a newer version of Windows.
The thread is placed in the online pool, using the ThreadPool.QueueUserWorkItem () method, which is the prototype of the following:
Puts a thread into the thread pool, and the start () method of the thread invokes the function represented by the WaitCallback proxy object
public static bool QueueUserWorkItem (WaitCallback);
The overloaded method is as follows, and the parameter object is passed to the method represented by the WaitCallback
public static bool QueueUserWorkItem (WaitCallback, object);
Attention:
The ThreadPool class is a static class and you cannot and will not have to generate its objects. And once you add a project to the thread pool using this method, the project will not be canceled.
Here you do not have to build the thread yourself, just write the work you want to do as a function, and then pass it as a parameter to the ThreadPool.QueueUserWorkItem () method, the method is to rely on the WaitCallback proxy object, and the thread of the establishment, management, Work is done automatically by the system, and you don't have to worry about complicated details.
Usage of ThreadPool:
First, the program creates a ManualResetEvent object that is like a semaphore that can use its signal to notify other threads.
In this example, when all the threads in the thread pool have finished working, the ManualResetEvent object is set to have a signal to inform the main thread to continue running.
There are several important ways to ManualResetEvent objects:
When initializing the object, the user can specify its default state (signal/no signal);
After initialization, the object retains its original state until its reset () or set () method is invoked:
Reset () Method: Set it to no signal state;
Set () Method: sets it to a signaled state.
WaitOne () Method: Causes the current thread to suspend until the ManualResetEvent object is in a signaled state, at which point the thread will be activated. The program then adds work items to the thread pool, which are used by the system to initialize the automatically established threads. When all the threads have run out, the Manualresetevent.set () method is invoked because the main thread that is in the waiting state receives the signal when the Manualresetevent.waitone () method is invoked, and then it goes down, Finish the work behind you.