.NET multi-thread programming (4): thread pool and asynchronous programming

zhaozj2021-02-16  43

.NET multi-thread programming (4): thread pool and asynchronous programming

If you read the three articles in front of me carefully, I believe that you have known the basic thread knowledge and multi-thread programming knowledge of the System.Threading.Thread class provided with .NET Framework and some thread synchronization. We will further discuss some .NET classes here, and how they play in multi-threaded programming. They are:

System.threading.ThreadPool class

System.threading.Timer class

If the number of threads is not a lot, and you want to control the details of each thread, such as thread priority, etc., using thread is relatively appropriate; but if there is a large number of threads, consider using thread pools should be better, it provides Efficient thread management mechanisms to handle multiple tasks. For regular execution tasks Timer class is appropriate; use the representative is the first choice for asynchronous method calls.

System.threading.threadpool class

When you create an application, you should recognize that most of your threads are idle waiting for some events (such as pressing a key or listening to the jacket). There is no doubt that you will think that this is absolute waste of resources.

If there are many tasks here, you need a thread every task, you should consider using thread pools to manage your resources more effectively and benefit from it. The thread pool is a plurality of threads that are executed, which allows you to add a thread automatically created and started to the queue. Use the thread pool to make your system to optimize the time fragmentation of threads when using CPU. But to remember at any specific point in time, each process and each thread pool has only one running thread. This class makes your thread that make up the pool to be managed, and your main energy is concentrated in the logic of workflow rather than the management of threads.

When the first instantiation ThreadPool class, the thread pool will be created. It has a default upper limit, that is, the up to 25 per processor, but this upper limit can be changed. This makes the processor will not be idle. If one of the threads waits for an event, the thread pool will initialize another thread and put it into the processor, the thread pool is the thread that is constantly created, and the assignment task gives those threads in the queue without work. The only limit is that the number of working threads cannot exceed the maximum allowable number. Each thread will run in the default priority and use the default stack of stacks that belong to multi-threaded space. Once a job task is added to the queue, you can't cancel.

Requesting the thread pool Processing a task or work item can call the QueueUserWorkItem method. This method takes a WaitCallback representative type parameter, which is packaged in the task of your medicine. Automatically create threads for each task and release threads when the task is released.

The following code illustrates how to create a thread pool and how to add a task:

Public void Afunction (Object O)

{

// do what Ever the function is support to do.

}

// Thread Entry Code

{

// Create An Instance of WaitCallback

Waitcallback mycallback = new waitcallback (afunction);

// add this to the thread pool / queue a task

ThreadPool.queueUserWorkItem (MyCallback);

}

You can also pass a system.threading.waithandle by calling the ThreadPool.RegisterWaitForsingleObject method, when the notification or time exceeds the call to be packaged by System.Threading.WaitortiMerCallback.

Thread pools and event-based programming modes make the thread pool to register for WaitHandles and the call to the appropriate waitorTimalCallback representative method is very simple (when WaitHandle is released). These practices are actually very simple. Here there is a constant observation of the thread queue waiting to operate. Once the operation is complete, a thread will be executed with its corresponding task. Therefore, this method adds a thread as the occurrence of the trigger event.

Let us see how to add a thread to the thread pool with an event, is actually very simple. We only need to create an event of a ManualResetEvent class and a representative of WaitortiMerCallback, and then we need a object carrying a representative status while we must decide the rest interval and execution. We add above to the thread pool and inspire an event: public void Afunction (Object O)

{

// do what Ever the function is support to do.

}

// Object That Will Carry The Status Info? o: P>

Public Class Anobject

{

}

// Thread Entry Code

{

// CREATE AN EVENT OBJECT?

ManualReveTevent aevent = new manualReveTevent (false);

// Create an Instance of WaitortimerCallback

Waitortimercallback thread_method = new waitorTimerCallback (Afunction);

// Create An Instance of Anobject

Anobject myobj = new anObject ();

// Decide How Thread Will Perform

INT TIMEOUT_INTERVAL = 100; // Timeout In Milli-Seconds.

Bool onetime_exec = true;

// add all this to the thread pool.

Threadpool. RegisterWaitforsingleObject (aevent, thread_method, myobj, timeout_interval, onetime_exec);

// raise the evenet

aevent.set ();

}

In the QueueUserWorkItem and RegisterWaitForsingleObject method, the thread pool creates a background thread to call back. When the thread pool begins to execute a task, both methods merge the caller's stack into the thread stack of the thread pool. If you need a security check to consume more time and increase the burden of the system, you can avoid security checks by using their corresponding unsafe methods. That is ThreadPool.unsafeRegisterWaitforsingleObject and ThreadPool.unsafequeueUserWorkItem.

You can also queue the task that is not related to waiting for operation. Timer-Queue Timers and Registered Wait Operations also uses the thread pool. Their return approach is also placed in the thread pool queue.

The thread pool is very useful and is widely used. Set of sub-programming on the NET platform, waiting for operation registration, process timer, and asynchronous I / O. For small and short tasks, the mechanism provided by the thread pool is also very convenient to be in multi-threaded. Thread pools are very convenient for completing many independent tasks and does not need to set up a thread attribute one by one. However, you should also be very clear, there are many cases that can be used in other ways to replace thread pools. For example, your planned task or give each thread-specific property, or you need to put the thread into a single thread space (and the thread pool is put in a multi-threaded space), or a specific task is Very lengthy, you'd better consider clear, safe approach is your choice than using the thread pool.

System.threading.timer Class

The Timer class is very effective for the periodic thread execution task, it cannot be inherited.

This class is especially used to develop console applications because system.windows.forms.time is unavailable. For example, to back up files and check the consistency of the database.

When you create a Timer object, your medication estimates the time between the first agent calls and the later successful calls. A timing call takes time in the process, and in later periodic calls. You can adapt to the Timer's CHANGE method to change the value of these settings or make Timer fail. When timer Timer is no longer used, you should call the Dispose method to release its resources. The TimerCallback representative is responsible for specifying the method associated with the Timer object (that is, the task to be performed during cycle) and status. It calls once and periodically calls this method until the DISPOSE method is called until the Dispose method is called until the Dispose method is called. The system automatically assigns separate threads.

Let's take a look at a code to see how things create Timer objects and use it. Let's first create a TimerCallback agent that is used in the later method. If needed, the next step we want to create a status object, which has specific information associated with the method called by the proxy. In order to make these simple, we pass an empty parameter. We will instantiate a Timer object, and then use the Change method to change the Timer setting, and finally call the Dispose method to release the resource.

// Class That Will Be Called by the Timer

Public Class WorkontimerReq

{

Public void atimelplathod ()

{

// does Some Work?

}

}

// Timer Creation Block

{

// instantiaating the class what gets caled by the timer.

WorkontimerReq Anobj = New WorkontimerReq ();

// Callback Delegate

Timercallback tcallback = new timercallback (anobj. Atimercallmeth);

// define the duetime and period

Long dtime = 20; // Wait Before The First Tick (In MS)

Long PTime = 150; // Timer During Subsequent Invocations (In MS)

// instantiate the Timer Object

Timer atimer = New Timer (TCALLBACK, NULL, DTIME, PTIME);

// do some think with the Timer Object

...

// Change the duetime and period of the time

DTIME = 100;

PTIME = 300;

Atimer.change (DTIME, PTIME);

// do something

...

atimer.dispose ();

...

}

Asynchronous programming

This part of this part is that it is a big part of it. Here, I don't plan to discuss this thing in detail, we just need until it is, because multi-thread programming If the multi-threaded programming of 忽 忽 is obviously not . Asynchronous multi-threaded programming is another multi-threaded programming method that your program may be used.

In the previous article, we spent a lot of space to introduce the synchronization of threads and how to achieve thread synchronization, but it has an inherent fattened shortcomings, you may notice this. That is, each thread must be synchronized, that is, waiting until the other functions, otherwise it will block. Of course, in some cases, it is sufficient for those logical mutual dependence. Asynchronous programming allows more complex flexibility. A thread can be modified asynchronous, do not wait for other things. You can use these threads as any task, and threads are responsible for getting the result to advance. This gives those who need a huge manner that requires a huge manner, and is not affordable to request a better system for enterprise-level systems that will wait for the price.

The .NET platform provides a consistent asynchronous programming mechanism for ASP.NET, I / O, Web Services, Networking, Message, and so on.

postscript

转载请注明原文地址:https://www.9cbs.com/read-23283.html

New Post(0)