namespace My_Samples { using System; using System.Threading; public class MyClass { public void MyMethod(object data) { Console.WriteLine(data.ToString()); } } class Program { static void Main(string[] args) { MyClass obj = new MyClass(); Thread thread = new Thread(obj.MyMethod); thread.Start("Hello world"); Console.WriteLine("Main method is completed..."); Console.ReadLine(); } } }
You are now more familier with this example. There are 2 threads in this example one is the main thread and other one is the user created thread. Both the threads share the time slice and the output is something similar as below.
Main Method - 0 My Method - 0 Main Method - 1 My Method - 1 Main Method - 2 My Method - 2 Main Method - 3 My Method - 3 Main Method - 4 My Method - 4 Main Method - 5 My Method - 5 Main Method - 6 My Method - 6 Main Method - 7 My Method - 7 Main Method - 8 My Method - 8 Main Method - 9 My Method - 9 Main method is completed... MyMethod completed...
Now let us introduce the Thread.Suspend, Thread.Resume and Thread.Abort code.
namespace My_Samples { using System; using System.Threading; public class MyClass { public void MyMethod() { for (int i = 0; i < 10; i++) { Console.WriteLine("My Method - " + i.ToString()); Thread.Sleep(50); } Console.WriteLine("MyMethod completed..."); } } class Program { static void Main(string[] args) { MyClass obj = new MyClass(); ThreadStart method = new ThreadStart(obj.MyMethod); Thread thread = new Thread(method); thread.Start(); for (int i = 0; i < 10; i++) { switch (i) { case 2: //Suspending now.. Console.WriteLine("Suspending the thread"); thread.Suspend(); break; case 5: //Resume the thread Console.WriteLine("Resuming the thread"); thread.Resume(); break; case 8: //Abort the thread Console.WriteLine("Aborting the thread"); thread.Abort(); break; default: break; } Console.WriteLine("Main Method - " + i.ToString()); Thread.Sleep(50); } Console.WriteLine("Main method is completed..."); Console.ReadLine(); } } }The output will be something similar as below.
Main Method - 0 My Method - 0 Main Method - 1 My Method - 1 Suspending the thread My Method - 2 Main Method - 2 Main Method - 3 Main Method - 4 Resuming the thread Main Method - 5 My Method - 3 Main Method - 6 My Method - 4 Main Method - 7 My Method - 5 Aborting the thread Main Method - 8 Main Method - 9 Main method is completed...
Since the code is simple enough to understand (Thanks to C# !!!) , I leave the remaining things to you.
No comments:
Post a Comment