3.1 Using ThreadStart delegates
Here is an example of the benefits of multithreading, first in the message class to establish a method ShowMessage (), which shows the current running thread ID, and use the Thread.Sleep (int) method to simulate part of the work. The ShowMessage () method of the Message object is bound by the ThreadStart delegate in Main (), and then the Async method is executed through Thread.Start ().
1 public class Message 2 {3 public void ShowMessage () 4 {5 String message = String. Format ("Async threadId is: {0}", 6 Thread.CurrentThread.ManagedThreadId); 7 Console.WriteLine (message); 8 9 for (int n = 0; n <) n++ {thread.sleep (300); Console.WriteLine ("The number is:" + n.tostring ()); }14}15}16 class Program18 {static void Main (string[] args ) {Console.WriteLine ("Main threadId is:" +22 thread.currentthr ead. MANAGEDTHREADID); message=new message (), thread thread = new Thread (new Threadstar T (message. showmessage)); thread. Start (); Console.WriteLine ("Do something ...!!!"); Console.WriteLine ("Main thread working is complete!"); 28 29}30}Note The result of the run, after calling the Thread.Start () method, the system runs Message.showmessage () asynchronously, and the operation of the main thread continues, before Message.showmessage () completes, The main thread has completed all operations.
3.2 Using Parameterizedthreadstart delegates
The Parameterizedthreadstart delegate is very similar to the ThreadStart delegate, but the Parameterizedthreadstart delegate is oriented with the parameter method. Note the argument to the Parameterizedthreadstart method is object, which can be either a value object or a custom object.
1 public class Person 2 {3 public string Name 4 {5 get; 6 set; 7 } 8 public int age 9 {get;11 set;12}13}14 public class M Essage16 {showmessage) (object person), (person = null) 20 {_person = (person) person;22 String message = String. Format ("\n{0} ' is {1}!\nasync threadId is:{2}", _person. Name,_person. Age,thread.currentthread.managedthreadid); Console.WriteLine (message);}26 for (int n = 0; n < n++) Thread.Sleep (300); Console.WriteLine ("The number is:" + n.tostring ()); }31}32}33 class Program35 {$ static void Main (string[] args) 37 { Console.WriteLine ("Main ThreadId is: "+thread.currentthread.managedthreadid)"; 41 message Message=new message (); To bind an asynchronous method with parameters
The thread thread = new Thread (The new Parameterizedthreadstart (message). ShowMessage)); person person = new person (); Name = "Jack"; Age = 21;46 Thread. Start (person); Start an asynchronous thread
Console.WriteLine ("Do something ...!!!!!"); Console.WriteLine ("Main thread working is complete!"); 50 51}52}Operation Result:
3.3 Foreground thread vs. background thread
Note that the above two examples do not use Console.readkey (), but the system will still wait for the asynchronous thread to complete before it ends. This is because the application domain is automatically unloaded after the thread Cheng that is started with Thread.Start () is considered a foreground thread, and the system must wait for all foreground threads to run.
In the second section, we introduced threads thread has a property isbackground, by setting this property to True, you can set the thread as a background thread! The application domain will be unloaded at the completion of the main thread without waiting for the asynchronous thread to run.
3.4 Suspending Threads
You can use the Thread.Sleep () method in order to wait for other background threads to finish before ending the main thread.
1 public class Message 2 {3 public void ShowMessage () 4 {5 String message = String. Format ("\nasync threadId is:{0}", 6 Thread.CurrentThread.ManagedThreadId); 7 Console.WriteLine (message); 8 for (int n = 0; n < n++) 9 {thread.sleep) Conso Le. WriteLine ("The number is:" + n.tostring ()),}13}14}15 class Program17 {s tatic void Main (string[] args) {Console.WriteLine ("Main threadId is:" +21 THREAD.CURRENTTHREAD.MANAGEDTHREADID); message message=new message (); 24 Thread thread = new Thread (The new ThreadStart (message). showmessage)); thread. IsBackground = true;26 Thread. Start (); Console.WriteLine ("Do something ...!!!!"); 29 Console.WriteLine ("Main thread working is complete!"); Console.WriteLine ("Main thread sleep!"); Thread.Sleep (5000); 32}33}
The result is as follows, when the application domain automatically ends after the main thread runs for 5 seconds
However, the system cannot predict how long an asynchronous thread needs to run, so blocking the main thread with thread.sleep (int) is not a good solution. In view of this,. NET specially developed another method thread for waiting for asynchronous threads to complete. Join (). Change the last line in the example above Thread.Sleep (5000) to thread. Join () guarantees that the main thread will not terminate until the thread thread of the asynchronous threads has finished running.
3.5 Suspend and Resume (use with caution)
Thread.Suspend () and Thread.Resume () are old methods that already exist in Framework1.0, and they can suspend and resume threads, respectively. But these two methods have been explicitly rejected in the Framework2.0. This is because once a thread occupies an existing resource, and then uses suspend () to keep the thread in a suspended state for a long time, it causes a deadlock when other threads invoke those resources! Therefore, the use of these two methods should be avoided in the absence of necessary conditions.
3.6 Terminating a thread
You can use the Abort () method if you want to terminate a running thread. When you use Abort (), a special exception ThreadAbortException is thrown.
If you want to resume the execution of a thread before it terminates, you can call Thread.resetabort () in the catch (ThreadAbortException ex) {...} after catching the exception to abort.
Using Thread.Join () ensures that the application domain waits for the asynchronous thread to end before terminating the run.
1 static void Main (string[] args) 2 {3 Console.WriteLine ("Main threadId is:" + 4 THREAD.CURRENTTHREAD.MANAGEDTHREADID); 5 6 Thread thread = new Thread (new ThreadStart (Asyncthread)); 7 Thread. IsBackground = true; 8 Thread. Start (); 9 Thread. Join (); 10 11} 12 13//Call asynchronously
+ static void Asyncthread () () {try17 {+] String message = String. Format ("\nasync threadId is:{0}", Thread.CurrentThread.ManagedThreadId), Console. WriteLine (message); (int n = 0; n < n++) 23 {24//when n equals 4 o'clock, terminates the thread
if (n >= 4)-Thread.CurrentThread.Abort (n); 2 8}29 Thread.Sleep, Console.WriteLine ("The number is : "+ n.tostring ());}32}33 catch (ThreadAbortException ex) 34 {3 5//Output value of n when terminating thread
if (ex. Exceptionstate = null) Notoginseng Console.WriteLine (String. Format ("Thread abort when the number is: {0}!", ". Exceptionstate.tostring ())); 39 40//Cancel termination, continue thread execution
Thread.resetabort (); Console.WriteLine ("Thread resetabort!"); 43}44 45//Thread End
Console.WriteLine ("Thread close!"); 47}
The operation results are as follows
C # implements multithreading in ThreadStart mode