Program in the Sample 00 can be converted to utilize the thread as follows.
using System;
using System.Threading;class Program {
static void Main(string[] args) {
Console.WriteLine("Main Started");
var th = new Thread(Greet); // Create new thread
th.Start(); // Execute Greet method in the created thread
Console.WriteLine("Main Completed");
Console.ReadKey();
}private static void Greet() {
Console.WriteLine("Hi, Good Morning!");
}
}
- Constructor of Thread class here, received the method to be invoked using a delegate called ThreadStart which is defined in BCL.
- Console application by default run in Main thread.
- During th.Start, runtime creates a new thread and starts the execution of Greet method in that thread.
- So the line after th.Start will continue to execute while Greet method is being executed in a new thread.
- Result will vary based on system performance.
Output
Main Started
Main CompletedHi, Good Morning!
No comments:
Post a Comment