In C# delay is given using Thread.Sleep(t) function with ‘t’ is representing time for which we want delay in milliseconds. For one second delay we write following statement.
Thread.Sleep(1000)
For two seconds delay give it ’2000′ as argument. Basically this function puts delay in your program by stopping the main program thread for the time mentioned.
Delay can also be given using a loop. A for loop or a while loop may be used for this purpose. It has an empty statement but it will iterate thousand of times which will take some time and will give us a delay.
Delay using for loop may be given as shown below
for(int i=0;i<500000;i++){
;//do nothing just waits
}
Also can be given using while loop as:
int i=0;while(i<500000){
i++;
}
But the preferred method is by using Thread.Sleep() method. Following code gives us an example of using this method.
Example:
Remember for using threads you need to include this line at top of your program for using threads and their features.
This is an example of delay in C# using both ways i.e Thread.Sleep() and loops.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace threads
{
class Program
{
public static void func1(){
while(true)
Console.WriteLine("Thread A running");
}
public static void func2()
{
while (true)
Console.WriteLine("Thread B running");
}
static void Main(string[] args)
{
//declaring two threads A & B
Thread A = new Thread(func1);
Thread B = new Thread(func2);
//starting thread A
Thread.Sleep(5000);//at start there will be delay of 5 seconds
A.Start();
for (int i = 0; i < 500000000; i++) {//another delay of almost 1 sec
;
}
//aborting thread A
A.Abort();
for (int i = 0; i < 500000000; i++)//one second delay after aborting thread A
{
;
}
//starting thread B
B.Start();
for (int i = 0; i < 500000000; i++)//one second delay after starting thread B
{
;
}
//aborting B
B.Abort();
//for pausing output
Console.ReadLine();
}
}
}