Thread.Sleep in Asp.net

 Posted on 12/10/2018

Share On: facebook gplus twitter

Threading is normally used to suspends the current thread for the specified amount of time to execute your own block of code. In this article, I will show you how you can use Threading with Sleep method. Lets take one example to run for loop here and display message in each 5 seconds for 3 times

using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading;
using
System.Threading.Tasks;

 namespace ExampleApp
{
   
class Program
    {
       
static void Main(string[] args)

        {
           
Console.WriteLine("Thread Start Now");

            for (int i = 0; i < 3; i++)
            {

                Console.WriteLine("Hello World " + i + " times execute after 5 seconds");
               
Thread.Sleep(5000);
            }

            Console.WriteLine("Thread Exit Now");

        }
    }
}

Output:

 

In above example, we used one for loop to execute output 3 times and 5 second waits for each. As we can see that in above output screensot.

Thread has two overloads with Sleep method

Sleep(Int32)
Suspends the current thread for the specified number of milliseconds. In this method, thread is suspended for specified milliseconds. Best practice is you should define your milliseconds in parameter.

Ex:

Thread.Sleep(5000);

Sleep(TimeSpan)            
Suspends the current thread for the specified amount of time. In this method, you need to define the time when thread should be suspended.

Ex:

TimeSpan TimeInterval = new TimeSpan(0, 10, 0);
Thread.Sleep(TimeInterval);

I hope it helps you to understand how Thread.Sleep work in Asp.Net
Add Comment:

Comments

This good
29/12/2018 1:02:09 PM   13:02:09   SAVAN BHAVASAR
This good
29/12/2018 1:02:08 PM   13:02:08   SAVAN BHAVASAR