Saturday, February 23, 2013

Threading: 06- Freezing a thread for a while- Thread.Sleep

We can make a thread sleep for a specific milliseconds. We can use this for testing the thread and asynchronous programming concepts and also we can use this to wait for a resource.

 

Example:

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
        th.Join();
        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);
    }
}

 

Above thread will waiting for 1 second (1000 milliseconds) before printing the greetings and after printing the greetings

No comments:

Post a Comment