What is the purpose of Thread.Sleep() method in .NET?

Thread.Sleep() method is used to block or suspend a thread for a specified time limit defined in milliseconds. This method is available in System.Threading namespace.



Here is an example:

public class sampleClass {
public static void Main() {
for (int index = 0; index < 2; index++) {
Console.WriteLine("Thread sleeps for next 5 seconds.");
System.Threading.Thread.Sleep(5000);
}
Console.WriteLine("Exit of Main Thread.");
}
}

Output of this code will be:

Thread sleeps for next 5 seconds
<cursor lies in the next line with a delay of 5 seconds>
Thread sleeps for next 5 seconds
<cursor lies in the next line with a delay of 5 seconds>
Exit of Main Thread.

Thread.Sleep method can accept the following as parameters:

• If you want to block the thread for a specific time period then specify an integer value (indicating time in milliseconds) as a parameter of Thread.Sleep method.
• If you want to block this thread so that other threads already waiting has to be executed, then you can do it by specifying Thread.Sleep(0)
• Specify Thread.Sleep(System.Threading.Timeout.Infinite) to block thread infinitely

| What is Private Access Modifier in C#? | What is Protected Access Modifier in C#? | What is Protected Internal Access Modifier in C#? | What is Public Access Modifier in C#? | What is the difference between virtual and abstract keywords in .NET? | What is the importance of Microsoft Application Blocks in .NET Architecture? | What is the need for Factory Method in C# | What is the purpose of ArrayList in .NET? | What is the purpose of Datareader in ADO.NET? | What is the purpose of Dataset in ADO.NET? | What is the purpose of finally block in C#? | What is the purpose of interlocked class in .NET? | What is the purpose of main() function in C# | What is the purpose of ManualResetEvent in .NET? | What is the purpose of sealed method in C#? | What is the purpose of Thread.Join() method in .NET? | What is the purpose of Thread.Sleep() method in .NET? | What is the purpose of throw keyword in C#? | What is the usage of ENUM in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.