Blocks the calling thread until the thread terminates, while continuing standard COM and SendMessage pumping. This method has different overloaded forms.
Pauses the thread for a period of time.
The Abort method is used to destroy the thread.
Let us see an example of Join() in thread -
using System; using System.Diagnostics; using System.Threading; namespace Sample { class Demo { static void Run() { for (int i = 0; i < 2; i++) Console.Write("Sample text!"); } static void Main(string[] args) { Thread t = new Thread(Run); t.Start(); t.Join(); Console.WriteLine("Thread terminated!"); Console.Read(); } } }
Let us see an example of abort() and sleep() in thread.
using System; using System.Threading; namespace Demo { class ThreadCreationProgram { public static void CallToChildThread() { try { Console.WriteLine("Child thread starts"); // do some work, like counting to 10 for (int counter = 0; counter <= 10; counter++) { Thread.Sleep(500); Console.WriteLine(counter); } Console.WriteLine("Child Thread Completed"); } catch (ThreadAbortException e) { Console.WriteLine("Thread Abort Exception"); } finally { Console.WriteLine("Couldn't catch the Thread Exception"); } } static void Main(string[] args) { ThreadStart childref = new ThreadStart(CallToChildThread); Console.WriteLine("In Main: Creating the Child thread"); Thread childThread = new Thread(childref); childThread.Start(); //stop the main thread for some time Thread.Sleep(2000); //now abort the child Console.WriteLine("In Main: Aborting the Child thread"); childThread.Abort(); Console.ReadKey(); } } }
The above is the detailed content of Join, Sleep and Abort methods in C# threads. For more information, please follow other related articles on the PHP Chinese website!