The below is a very simple example. We added the namespace 'System.Threading' in using section. Then we added a static method (this is just for example, avoid using static methods as much as possible. Why? we will see later.). In the main method, we created an entry point. You know that every application should have an entry point. In Console application and winforms application, it is Main() method. As like the thread will also have an entry point. The entry point is created with the ThreadStart class. Then we created a Thread object and passed the entryPoint (ThreadStart) to the thread object. Then we started the thread. Thats it.
namespace My_Samples { using System; using System.Threading; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication2 { class Program { public static void MyMethod() { for (int i = 0; i < 10; i++) { Console.WriteLine("My Method - " + i.ToString()); Thread.Sleep(1000); } Console.WriteLine("MyMethod completed..."); } static void Main(string[] args) { ThreadStart entryPoint = new ThreadStart(MyMethod); Thread thread = new Thread(entryPoint); thread.Start(); for (int i = 0; i < 10; i++) { Console.WriteLine("Main Method - " + i.ToString()); Thread.Sleep(1000); } Console.WriteLine("Main completed..."); Console.ReadLine(); } } } }
The output will look something similar as below.
Main Method - 0 My Method - 0 Main Method - 1 Main Method - 2 My Method - 1 Main Method - 3 Main Method - 4 My Method - 2 Main Method - 5 My Method - 3 Main Method - 6 Main Method - 7 My Method - 4 Main Method - 8 Main Method - 9 My Method - 5 Main completed... My Method - 6 My Method - 7 My Method - 8 My Method - 9 MyMethod completed...
Since it is equal time slice you may notice the pattern the MyMethod executes once (as it sleeps for 1000 milliseconds) and the Main method executes twice (as it only sleeps 500 milliseconds)
No comments:
Post a Comment