We can wait for a thread to complete, but we cannot wait indefinitely sometimes. .Net allows us to wait for a thread to complete just for a while, using Thread.Join method.
Thread.Join method, receives a timeout in milliseconds and waits up to that period. If it is still running, it stops waiting and returns false, else returns true.
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(new object[] { "Bob", "Good Morning" }); // Execute Greet method in the created thread
if (th.Join(800))
Console.WriteLine("Greeting finished");
else
Console.WriteLine("Greeting is still running");
Console.WriteLine("Main Completed");
Console.ReadKey();
}private static void Greet(object info) {
Thread.Sleep(1000);
Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
Thread.Sleep(1000);
}
}
Output:
Main Started
Greeting is still running
Main Completed
Hi Bob, Good Morning!
No comments:
Post a Comment