Table of Contents
Working of C# Thread Sleep
Examples to Implement Thread Sleep in C#
Example #2
Conclusion
Recommended Article

C# Thread Sleep

Sep 03, 2024 pm 03:25 PM
c# c# tutorial

The thread that is executing currently can be paused or temporarily suspended for a specified amount of time using a method in C# called Sleep() method and the amount of time must be specified in milliseconds and passed as a parameter to the thread we are trying to suspend or by using timespan property in which there is a privilege to specify the time in hours, minutes and seconds so that the thread can be paused for a longer time as well as per our need and not just for milliseconds.

Syntax:

Thread.Sleep(Time_in_milliseconds);
Copy after login

Or

TimeSpaninstance_name = new TimeSpan(Time_in_hours_minutes_seconds);
Thread.Sleep(instance_name);
Copy after login

Where instance_name is the name of the instance of TimeSpan class.

Working of C# Thread Sleep

  • Whenever there is a need to pause the execution of a thread so that other thread can take over and start execution, we make use of the method called Sleep() method.
  • The amount of time a thread needs to be paused can be specified in either millisecond and passed as a parameter to Sleep() method or it can be specified in hours, minutes, and seconds using timespan property.
  • ArgumentOutOfRangeException is thrown by the Sleep() method if the time in milliseconds passed as a parameter to it is negative.
  • ArgumentOutOfRangeException is thrown by the Sleep() method if the time passed as a parameter to timespan property is negative.
  • If the time in milliseconds passed as a parameter to the Sleep() method is zero, then the other thread of the same priority which is ready to run starts execution.
  • If the time passed as a parameter to the timespan property is zero, then the other thread of the same priority which is ready to run starts execution.

Examples to Implement Thread Sleep in C#

Below are the examples of C#Thread Sleep:

Example #1

C# program to demonstrate Sleep() method with time in milliseconds passed as a parameter.

 Code:

using System;
using System.Threading;
//a class called program is created
public class program
{
//a method called samplemethod which accepts a parameter is created
public void samplemethod(object str)
{
for (int z = 0; z < 5; z++)
{
Console.WriteLine("The thread that is executing is {0}", str);
Thread.Sleep(200);
}
}
}
//a class called check is created
public class check
{
//main method is called
public static void Main()
{
//two string variables are created which are passed as parameter previously created method in program class
string Iamthread1 = null;
string Iamthread2 = null;
//an instance of the program class is created
program d = new program();
Thread firstthread = new Thread(new ParameterizedThreadStart(d.samplemethod));
Thread secondthread=new Thread(new ParameterizedThreadStart(d.samplemethod));
firstthread.Start("Iamthread1");
secondthread.Start("Iamthread2");
}
}
Copy after login

Output:

C# Thread Sleep

Explanation: In the above program, a namespace called a program is created within which a method called sample method, which accepts a parameter is created inside which the thread that operates on the method is paused for a certain time by using Sleep() method. Then a class called check is created within which the main method is called in which the two instances of threads are created and then begins their execution on sample method using Start() method. Since Sleep() method is used on the threads operating on the sampling method, the threads are not executed in a row.

Example #2

C# program to demonstrate Sleep() method using TimeSpan property.

Code:

using System;
using System.Threading;
//a class called program is created
public class program
{
//a method called samplemethod which accepts a parameter is created
public void samplemethod(object str)
{
//TimeSpan property is used to specify the duration of time for which the thread must be paused
TimeSpan timeout = new TimeSpan(0, 0, 3);
for (int z = 0; z < 3; z++)
{
Console.WriteLine("The thread that is executing is {0}", str);
Thread.Sleep(timeout);
}
}
}
//a class called check is created
public class check
{
//main method is called
public static void Main()
{
//two string variables are created which are passed as parameter previously created method in program class
string Iamthread1 = null;
string Iamthread2 = null;
//an instance of the program class is created
program d = new program();
Thread firstthread = new Thread(new ParameterizedThreadStart(d.samplemethod));
Thread secondthread = new Thread(new ParameterizedThreadStart(d.samplemethod));
firstthread.Start("Iamthread1");
secondthread.Start("Iamthread2");
}
}
Copy after login

Output:

C# Thread Sleep

Explanation: In the above program, a namespace called a program is created within which a method called sample method which accepts a parameter is created inside which the thread that operates on the method is paused for a certain time by using TimeSpan property. Then a class called check is created within which the main method is called in which the two instances of threads are created and then begins their execution on sample method using Start() method. Since the Sleep() method is used on the threads operating on the sampling method, the threads are not executed in a row. The output is shown in the snapshot above.

Conclusion

In this tutorial, we understand the concept of the ThreadSleep method in C# through definition, syntax, and working of the ThreadSleep method through programming examples and their outputs.

Recommended Article

This is a guide to C# Thread Sleep. Here we discuss the Introduction to C# Thread Sleep and its working along with its examples and Code Implementation. You can also go through our other suggested articles to learn more –

  1. What is Random Number Generator in C#?
  2. Static Constructor in Java | Working | Applications
  3. TextWriter in C# | Examples
  4. How to Work Static Constructor in C#?

The above is the detailed content of C# Thread Sleep. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

See all articles