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()); 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++) Console.WriteLine("Main Method - " + i.ToString()); Console.WriteLine("Main method is completed..."); Console.ReadLine(); } } }
The output that you will see is something similar below.
Main Method - 0 My Method - 0 My Method - 1 My Method - 2 My Method - 3 My Method - 4 My Method - 5 My Method - 6 My Method - 7 My Method - 8 My Method - 9 MyMethod completed... Main Method - 1 Main Method - 2 Main Method - 3 Main Method - 4 Main Method - 5 Main Method - 6 Main Method - 7 Main Method - 8 Main Method - 9 Main method is completed...
So the main method executes and completes first and then the thread method follows (Since the execution time of Main method is less than the time slice allotted, we don't see the switch between the main method and the thread method). Now let's set some priority for the main method and the thread method.
MyClass obj = new MyClass(); ThreadStart method = new ThreadStart(obj.MyMethod); Thread thread = new Thread(method); thread.Start(); thread.Priority = ThreadPriority.Highest; Thread.CurrentThread.Priority = ThreadPriority.Lowest;
Now we set the thread's priority to highest and set the Main method (Current Thread) priority to lowest. Now you will see the output as,
My Method - 0 My Method - 1 My Method - 2 My Method - 3 My Method - 4 My Method - 5 My Method - 6 My Method - 7 My Method - 8 My Method - 9 MyMethod completed... Main Method - 0 Main Method - 1 Main Method - 2 Main Method - 3 Main Method - 4 Main Method - 5 Main Method - 6 Main Method - 7 Main Method - 8 Main Method - 9 Main method is completed...
Since we set the thread's priority as highest, the thread method completes first and then the main method follows. The result is just reverse now. I hope now you know the importance of setting the priority. The following are the options where .net provides to us.
ThreadPriority.Highest;
ThreadPriority.Lowest;
ThreadPriority.Normal;
ThreadPriority.AboveNormal;
ThreadPriority.BelowNormal;
No comments:
Post a Comment