C # multi-thread teaching (4): thread pool and asynchronous programming

Source: Internet
Author: User

Review of the first three chapters:C #. Net multi-thread programming teaching (3): Thread SynchronizationC #. Net multi-thread programming teaching (2): Thread class C #. Net multi-thread programming teaching (1): multi-task and multi-thread

If you carefully read the first three articlesArticleI believe that you are familiar with the basic thread knowledge and multi-thread programming knowledge of the system. Threading. Thread class provided by. NET Framework and some thread synchronization classes. We will further discuss some. Net classes here, as well as their roles in multi-threaded programming and how to program them. They are:

System. Threading. threadpool class

System. Threading. Timer class

If the number of threads is not large, and you want to control the details of each thread, such as the thread priority, it is more appropriate to use the thread; but if there are a large number of threads, it should be better to use the thread pool. It provides an efficient thread management mechanism to process multiple tasks. It is suitable for the Timer class of scheduled execution tasks, and usage indicates that it is the first choice for Asynchronous Method calls.

System. Threading. threadpool class

When you create an applicationProgramYou should realize that most of the time your thread is idle waiting for some events to occur (such as pressing a key or listening for requests of the child node ). Without a doubt, you will think this is an absolute waste of resources.

If many tasks need to be completed and each task requires a thread, you should consider using the thread pool to manage your resources more effectively and benefit from it. A thread pool is a collection of multiple threads that are executed. It allows you to add tasks automatically created and started by threads to the queue. Using the thread pool allows your system to optimize the time fragmentation of threads during CPU usage. But remember that at any specific point in time, each process and each thread pool have only one running thread. This class enables the system to manage the pool composed of your threads, so that your main focus is on workflow logic rather than thread management.

When the threadpool class is instantiated for the first time, the thread pool is created. It has a default upper limit, that is, each processor can have up to 25, but this upper limit can be changed. In this way, the processor will not be idle. If one of the threads waits for an event, the thread pool initializes another thread and puts it into processing, the thread pool is the way in which jobs are constantly created and tasks are allocated to threads in the queue that are not working. The only limit is that the number of worker threads cannot exceed the maximum allowed number. Each thread will run at the default priority and use the default stack size space that belongs to the multi-thread space. Once a job is added to the queue, you cannot cancel it.

The queueuserworkitem method can be called to request the thread pool to process a task or work item. This method includes a waitcallback parameter of the type, which encapsulates the task completed by your medicine. The runtime automatically creates a thread for each task and releases the thread when the task is released.

The followingCodeDescribes how to create a thread pool and add tasks:

Public void afunction (Object O)

{

// Do what ever the function is supposed 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 call the threadpool. registerwaitforsingleobject method to pass a system. Threading. waithandle. When the notification or time exceeds the time of calling the method encapsulated by system. Threading. waitortimercallback.

The thread pool and event-based programming mode make the thread pool monitor registered waithandles and the appropriate waitortimercallback to indicate that method calls are very simple (when waithandle is released ). These practices are actually very simple. Here, a thread constantly observes the status of waiting for operations in the thread pool queue. Once the operation is completed, a thread is executed with the corresponding task. Therefore, this method adds a thread as the trigger event occurs.

Let's take a look at how to add a thread to the thread pool with the event, which is actually very simple. We only need to create a manualresetevent class event and a waitortimercallback representative. Then we need an object that carries the status, and we also need to determine the break interval and execution method. We add all of the above to the thread pool and trigger an event:

Public void afunction (Object O)

{

// Do what ever the function is supposed to do.

}

// Object that will carry the status information

Public class anobject

{

}

// Thread entry code

{

// Create an event object

Manualresetevent aevent = new manualresetevent (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 event

Aevent. Set ();

}

In the queueuserworkitem and registerwaitforsingleobject methods, the thread pool creates a background thread to call back and forth. When the thread pool starts executing a task, both methods merge the caller's stack into the thread stack of the thread pool. If security checks are required, it will take more time and increase the burden on the system. Therefore, you can avoid security checks by using their corresponding insecure methods. It is threadpool. unsaferegisterwaitforsingleobject and threadpool. unsafequeueuserworkitem.

You can also queue tasks unrelated to the waiting operation. Timer-queue timers and registered wait operations also use thread pools. Their return methods are also put into the thread pool queue.

The thread pool is very useful and widely used. 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 in multithreading. The thread pool is very convenient for completing many independent tasks without setting thread attributes one by one. However, you should also be clear that there are many situations where you can use other methods to replace the thread pool. For example, you plan a task or give specific attributes to each thread, or you need to put the thread into the space of a single thread (and the thread pool is to put all the threads into a multi-thread space ), or a specific task is very lengthy. In these cases, you 'd better consider clearly that the security method should be your choice over using the thread pool.

System. Threading. Timer class

The timer class is very effective for periodically executing tasks in separated threads and cannot be inherited.

This class is especially used to develop console applications, because system. Windows. Forms. Time is unavailable. For example, backup files and check Database Consistency.

When you create a timer object, you can estimate the time between the waiting time before the first proxy call and the time between each successful call. A scheduled call occurs in the time that the method takes, and periodically calls this method later. You can adapt to the change method of timer to change the value of these settings or make timer invalid. When the timer is no longer used, you should call the dispose method to release its resources.

Timercallback specifies the method (the task to be periodically executed) and status associated with the timer object. It calls the method once after the time it deserves, and periodically calls the method until the dispose method is called to release all the resources of the timer. The system automatically allocates separate threads.

Let's look at a piece of code to see how to create a timer object and use it. First, we need to create a timercallback proxy, which will be used in subsequent methods. If necessary, create a State object that has specific information associated with the method called by the proxy. To make these simple, we pass an empty parameter. We will instantiate a timer object, then use the change method to change the timer settings, and finally call the dispose method to release resources.

// Class that will be called by the timer

Public class workontimerreq

{

Public void atimercallmethod ()

{

// Does some work

}

}

// Timer creation Block

{

// Instantiating the class that gets called by the timer.

Workontimerreq anobj = new workontimerreq ();

// Callback delegate

Timercallback tcallback = new timercallback (anobj. atimercallmethod );

// 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 thing with the timer object

...

// Change the duetime and period of the timer

Dtime = 100;

Ptime = 300;

Atimer. Change (dtime, ptime );

// Do some thing

...

Atimer. Dispose ();

...

}

Asynchronous programming

If you want to clarify this part, it is a huge part. Here, I am not going to discuss it in detail, we just need to wait until it is what it is, multi-thread programming is obviously not appropriate if asynchronous multi-thread programming is abnormal. Asynchronous multi-thread programming is another multithreaded programming method that your program may use.

In the previous article, we spent a lot of time introducing thread synchronization and how to implement thread synchronization. However, it has an inherent fatal drawback. You may have noticed this. That is, each thread must make a synchronous call, that is, wait until other functions are completed, otherwise it will be blocked. Of course, in some cases, it is sufficient for logically dependent tasks. Asynchronous programming allows more complex flexibility. A thread can be called asynchronously without waiting for anything else. You can use these threads to execute any task, and the threads are responsible for obtaining the results and promoting the running. This gives enterprise-level systems that need to manage a large number of requests and are unable to afford the cost of waiting for requests for better scalability.

The. NET platform provides consistent asynchronous programming mechanisms for ASP. NET, I/O, web services, networking, and message.

Postscript

Since it is difficult to find Chinese materials during study, I had to learn English materials. Due to the low level, the meaning of the original text may be misinterpreted during translation, I hope you can point out that, at the same time, we hope that these things will give you some reference and help in learning this knowledge. Even a little bit, I am very pleased.

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.