.NET multi-threaded preliminary (1)

xiaoxiao2021-03-06  22

Several basic methods for THREAD class 1.Start, Join and Sleep are the most basic, start, destruction and delay of thread operation. Using system; using system.threading;

public class StartJoinSleep {public static void Main () {ThreadStart myThreadStart = new ThreadStart (firstThread); Thread myThread = new Thread (myThreadStart); myThread.Start (); Thread.Sleep (1000); Console.WriteLine ( "Now execute join "); mythread.abort (); mythread.join (); console.writeline (" main trread end.press any key exit "); console.readline ();} private static void firstthread () {for (int i = 1; i <= 100; i ) {Console.Writeline ("First Thread Running. and loop Times IS {0}.", i); thread.sleep (200);}}}

2.Abort and resetabortabort trigger ThreadAbortexception on the thread calling this method to begin terminating this thread. Calling this method usually terminates the thread. Usually with resetabort to block ThreadAbortException end threads to continue to perform the code example in FINALLY: Using System; Using System.Threading;

public class AbortResetAbort {public static void Main () {ThreadStart myThreadStart = new ThreadStart (Work); Thread myThread = new Thread (myThreadStart); myThread.Start (); Thread.Sleep (300); Console.WriteLine ( "Now execute Abort "); Mythread.abort (); mythread.join (); console.writeline (" main trread ending.press any key exit "); console.readline ();}

Public static void work () {try {for (INT i = 0; I <100; I ) {Console.writeline ("Thread - Working."); thread.sleep (100);}} catch (threadabortext) { Console.WriteLine ( "Thread - caught ThreadAbortException - resetting."); Console.WriteLine ( "Exception message: {0}", e.Message); Thread.ResetAbort ();} Console.WriteLine ( "Thread - still alive and ""); thread.sleep (1000); console.writeline ("Thread - finished working.");}} 3. Suspend and resumes for threads; use systems; use system.threading; public class suspendresume { public static void Main () {ThreadStart myThreadStart = new ThreadStart (Work); Thread myThread = new Thread (myThreadStart); myThread.Start (); Thread.Sleep (500); Console.WriteLine ( "Now execute Suspend Method.2000ms" ); Mythread.suspend (); thread.sleep (2000); mythread.Resume (); mythread.join (); console.writeline ("main thread ending.press any key exit); console.readline ();}

Public static void work () {for (int i = 1; i <21; i ) {console.writeline ("Thread loop Times IS {0}.", i); threeRead.sleep (100);}}} 4 When the thread is interrupted next time in Wait, Sleep or JOIN status, the following example can view the difference between the number of cycles in the thread before the interrupt execution is 500ms and 550ms, which can be clearly seen. Using system; using system.threading;

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

New Post(0)