Thread signal mechanism and thread signal Mechanism

Source: Internet
Author: User

Thread signal mechanism and thread signal Mechanism

From: http://www.cnblogs.com/willick/p/4177977.html for reference only

Sometimes you need a thread to start executing when it receives a signal. Otherwise, the thread is in the waiting state. This is a signal-based event mechanism .. NET Framework provides a ManualResetEvent class to process such events. Its WaiOne instance method can keep the current thread in the waiting state until it receives a signal. Its Set method is used to enable the sending signal. The following is an example of signal mechanism usage:

1 // thread signal Mechanism 2 # region 3 var signal = new ManualResetEvent (false); 4 DateTime beginTime = DateTime. now; 5 new Thread () => {6 Console. writeLine ("waiting for signal... "); 7 signal. waitOne (); 8 signal. dispose (); 9 Console. writeLine ("Got signal"); 10 }). start (); 11 Thread. sleep (2000); 12 TimeSpan ts = (DateTime. now-beginTime); 13 Console. writeLine ("consumed" + ts. totalMilliseconds); 14 signal. set (); 15 16 Console. readKey (); 17 # endregion

Effect:

1 waiting for signal... 2 has consumed 2003.11453 Got signal

After the Set method is executed, the signal remains open. You can use the Reset method to disable it. If you do not need it, release it through Dispose. If the expected waiting time is short, you can use ManualResetEventSlim to replace ManualResetEvent. The former has better performance than the short-term waiting time. The signal mechanism is very useful and will be used in subsequent log cases.

Threads in the thread pool

The threads in the thread pool are managed by CLR. In the following 2 conditions, the thread pool can play the best effect:

* The task runs in a short time (<250 ms). In this way, the CLR can fully allocate existing Idle threads to process the task;

* Tasks that are waiting (or congested) for a large amount of time do not control the threads in the thread pool.

1 // Method 1: Task. run ,. NET Framework 4.5 only has 2 tasks. run () => Console. writeLine ("Hello from the thread pool"); 3 4 // Method 2: ThreadPool. queueUserWorkItem5 ThreadPool. queueUserWorkItem (t => Console. writeLine ("Hello from the thread pool "));

Case: Support for concurrent asynchronous log Components

Based on the above knowledge, we can implement the function of writing logs concurrently in applications. In applications, log writing is a common function. You can analyze the requirements of this function:

1 public class Logger 2 {3/* 4*1. A queue is required to store the log writing task. A signal mechanism is required to identify whether a new task needs to be executed 6*3. when a new log writing task exists, add the task to the queue and send a signal 7*4. A method is used to process tasks in the queue. When receiving new task signals, the tasks in the queue are called 8*5 in sequence. the lock object must implement the lock operation on the inbound and outbound stacks to ensure that no operation is performed on the outbound stacks 9 */10 private Queue <Action> queue; 11 private ManualResetEvent switchSignal; 12 private Thread loggingThread; 13 private static readonly Logger log = new Logger (); 14 public static Logger GetIntence () 15 {16 return log; 17} 18 private Logger () 19 {20 queue = new Queue <Action> (); 21 switchSignal = new ManualResetEvent (false ); 22 loggingThread = new Thread (ReceiveInfo); 23 loggingThread. isBackground = true; 24 loggingThread. start (); 25} 26 private void ReceiveInfo () 27 {28 switchSignal. waitOne (); 29 switchSignal. reset (); 30 31 Thread. sleep (100); 32 Queue <Action> oldQueue; 33 lock (queue) 34 {35 oldQueue = new Queue <Action> (queue); 36 queue. clear (); 37} 38 foreach (var action in oldQueue) 39 {40 action (); 41} 42} 43 // Add 44 public void WriteLog (string content) to the task) 45 {46 lock (queue) // thread security issues may occur and may be blocked. 47 {48 queue. enqueue () => File. appendAllText ("log.txt", content); 49} 50 switchSignal. set (); 51} 52 public static void BeginLog (string content) 53 {54 Task. factory. startNew () => GetIntence (). writeLog (content); // 4.0 does not support tasks. run (); 55} 56}
1 static void Main (string [] args) 2 {3 Thread t1 = new Thread (Working); 4 t1.Name = "Thread1"; 5 Thread t2 = new Thread (Working ); 6 t2.Name = "Thread2"; 7 Thread t3 = new Thread (Working); 8 t3.Name = "Thread3"; 9 10 // start three threads in sequence. 11 t1.Start (); 12 t2.Start (); 13 t3.Start (); 14 15 Console. readKey (); 16} 17 18 // each thread is Working 19 static void Working () 20 {21 // simulate 1000 log write operations 22 for (int I = 0; I <1000; I ++) 23 {24 // asynchronously write the file 25 Logger. beginLog (Thread. currentThread. name + "writes a log:" + I + ", on" + DateTime. now. toString () + "\ r \ n"); 26} 27} 28}

The purpose of this example is to let everyone know the basic applications and precautions of threads and concurrency in development.

Unfortunately, this Logger class is not perfect, and there is a thread security problem (marked in red in the Code), although the actual environment probability is very small. It may be difficult to see exceptions when the above Code is run multiple times (I have not run exceptions many times), but adding several threads at the same time may cause problems.

 

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.