C # threads from unfamiliar to familiar (3)

Source: Internet
Author: User

Let's talk about the thread pool today:

Applications can have multiple threads, which consume a lot of time to wait for an event to occur in sleep state. Other threads may enter sleep state, and are only regularly awakened to change or update status information in a round robin manner, and then enter sleep state again. To simplify the management of these threads ,. net Framework provides a thread pool for each process. A thread pool has several waiting operation statuses. When a waiting operation is completed, the auxiliary thread in the thread pool executes the callback function. Threads in the thread pool are managed by the system. programmers can concentrate on application tasks without having to perform thread management. A thread pool is provided through the threadpool class in the base class library. This thread pool can be used to send work cash streams and process asynchronous I/O, representing other threads waiting and processing timers. all methods of the threadpool class are static methods. threadpool itself is also a static class.
Let's take a look at his definition and some common methods:
Public static class threadpool
{
[Securitysafecritical]
Public static void getavailablethreads (Out int workerthreads, out int completionportthreads );
[Securitysafecritical]
Public static void getmaxthreads (Out int workerthreads, out int completionportthreads );
[Securitysafecritical]
Public static void getminthreads (Out int workerthreads, out int completionportthreads );
[Securitysafecritical]
Public static bool queueuserworkitem (waitcallback callback );
[Securitysafecritical]
Public static bool queueuserworkitem (waitcallback callback, object State );
}
The difference between the maximum number of threads in the thread pool returned by the getavailablethreads method and the number of active threads. Workerthreads: number of available auxiliary threads. Completionportthreads: number of available asynchronous I/O threads.
The getmaxthreads method obtains the maximum number of auxiliary threads maintained by the thread pool. Parameter workerthreads: Maximum number of auxiliary threads in the thread pool. Completionportthreads: the maximum number of idle asynchronous I/O threads maintained by the thread pool.
The getminthreads method obtains the minimum number of idle auxiliary threads maintained by the thread pool. workerthreads: the minimum number of idle auxiliary threads maintained by the thread pool. completionportthreads: the minimum number of idle asynchronous I/O threads maintained by the thread pool.
The queueuserworkitem method queues methods for execution. The callback parameter indicates the method to be executed. State: the object that contains the data used by the method.
The following is an example:

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5 using system. Threading;
6
7 namespace consoleapplication6
8 {
9 class Program
10 {
11 static void main (string [] ARGs)
12 {
13 console. writeline ("using the main thread for asynchronous entry ");
14
15 autoresetevent asyncopisdone = new autoresetevent (false );
16 threadpool. queueuserworkitem (New waitcallback (x) =>
17 {
18
19 thread. Sleep (1000 );
20 console. writeline ("job ");
21
22 }));
23 string S = "My Parameters ";
24 threadpool. queueuserworkitem (New waitcallback (x) =>
25 {
26
27 thread. Sleep (2000 );
28 console. writeline ("Job 1 ");
29 console. writeline (X );
30
31}), S );
32 threadpool. queueuserworkitem (New waitcallback (myasyncoperation), asyncopisdone );
33 console. writeline ("other main thread execution ");
34 console. writeline ("the main thread waits for the task to finish processing ");
35 asyncopisdone. waitone ();
36}
37 static void myasyncoperation (object state)
38 {
39
40 thread. Sleep (5000 );
41 console. writeline ("job 2 ");
42 (autoresetevent) State). Set ();
43}
44}
45}

 

The running result is

Here, there is a class autoresetevent, which is used to notify the waiting thread that an event has occurred. It is inherited from eventwaithandle! In this example, two different calling methods are used, and the second one is parameter passing! Worker thread 1 passes the "My Parameters" string! When worker thread 2 is finished, an event will be reported to the waiting thread. here, when autoresetevent is initialized, the signal is set to false first, and worker thread 2 is set to true if the call is successful. asyncopisdone. waitone () blocks the current thread until it receives a signal!

Let's look at the example below.

 

 

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5 using system. Threading;
6
7 namespace consoleapplication7
8 {
9 class Program
10 {
11 static void main (string [] ARGs)
12 {
13 console. writeline ("\ n current thread's hashcode: {0}", thread. currentthread. gethashcode (). tostring ());
14 console. writeline ("current application domain name: {0}", appdomain. currentdomain. friendlyname );
15 int workerthreads;
16 int completionportthreads;
17
18 autoresetevent asyncopisdone = new autoresetevent (false); // The signal is empty initially.
19 autoresetevent asyncopisdone2 = new autoresetevent (false );
20 threadpool. queueuserworkitem (New waitcallback (mywork), asyncopisdone );
21 threadpool. queueuserworkitem (New waitcallback (mywork1), asyncopisdone2 );
22 threadpool. getmaxthreads (Out workerthreads, out completionportthreads );
23 console. writeline ("Maximum number of auxiliary threads maintained by the thread pool: {0}", workerthreads );
24 threadpool. getminthreads (Out workerthreads, out completionportthreads );
25 console. writeline ("minimum number of idle auxiliary threads maintained by the thread pool: {0}", workerthreads );
26/* waithandle [] waithandles = new waithandle [2];
27 waithandles [0] = asyncopisdone;
28 waithandles [1] = asyncopisdone2;
29 waithandle. waitall (waithandles );*/
30 // or you can
31 asyncopisdone. waitone ();
32 console. writeline ("mywork ended ");
33 asyncopisdone2.waitone ();
34 console. writeline ("mywork1 ended ");
35}
36 static void mywork (object state)
37 {
38 console. writeline ("\ n current thread's hashcode: {0}", thread. currentthread. gethashcode (). tostring ());
39 console. writeline ("current application domain name: {0}", appdomain. currentdomain. friendlyname );
40 thread. Sleep (2000 );
41 (autoresetevent) State). Set (); // indicates that the work has been completed.
42}
43 static void mywork1 (object state)
44 {
45 console. writeline ("\ n current thread's hashcode: {0}", thread. currentthread. gethashcode (). tostring ());
46 console. writeline ("current application domain name: {0}", appdomain. currentdomain. friendlyname );
47 thread. Sleep (1000 );
48 (autoresetevent) State). Set (); // indicates that the work has been completed.
49}
50
51}
52}

 

The running result is

 

In this example, you can see in detail the use of autorestevent mywork1 actually ended first, but asyncopisdone needs to wait for the signal of mywork! So I output mywork first. Here is another thing I want to talk about: waithandle. The above example has provided his usage! It is the base class of autorsetevent.

There is also threadpool, which has a function registerwaitforsingleobject. This function is quite interesting! I will not give an example here!

Now, it's today!

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.