Tuesday 21 August 2018

Thread: Sleep: make the thread to sleep

Thread class provides 'Sleep' method, it makes the thread to sleep for given amount of time.

'Sleep' method is available in following two overloaded forms.

Sleep(Int32)
Sleep(TimeSpan)

Example
Thread.Sleep(1000); // Sleep for 1 seconds
Thread.Sleep(TimeSpan.FromSeconds(3)); // Sleep for 3 seconds

Program.cs
using System.Threading;
using System;

namespace ThreadingTutorial
{
    class HelloWorld
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(print);

            t1.Name = "Thread1";

            t1.Start();
           
        }

        public static void print()
        {
            Console.WriteLine(Thread.CurrentThread.Name  + " Executing");
            Thread.Sleep(1000); // Sleep for 1 seconds
            Thread.Sleep(TimeSpan.FromSeconds(3)); // Sleep for 3 seconds
            Console.WriteLine(Thread.CurrentThread.Name + " Finished execution");
        }
    }
}

Output
Thread1 Executing
Thread1 Finished execution



Previous                                                 Next                                                 Home

No comments:

Post a Comment