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.



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
        Console.WriteLine("Main Completed");

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);


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

No comments:

Post a Comment