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(1000); } 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()); Thread.Sleep(500); } Console.WriteLine("Main completed..."); Console.ReadLine(); } } }
Access instance object's methods
Lets see an another simple example. In our earlier example we provided the static method as entry point for the thread. Now we will provide a instance method as entry point to the thread. The program is straight forward. We declared a class 'MyClass' and moved the method from the class 'Program' to 'MyClass' and then moidified it as non-static method (removed the static keyword). In the Main method, we created an object for 'MyClass' and then we passed the instantiated object's method to the Thread start method. So again now this so simple for you right... Lets keep exploring further deatils of threads in later articles.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment