Certainly! Here’s an example of using the Sleep()
method in C# to introduce a delay in a separate thread:
using System; using System.Threading; class Program { static void Main() { // Create a new thread and start it Thread thread = new Thread(CountNumbers); thread.Start(); // Perform some other tasks in the main thread for (int i = 1; i <= 5; i++) { Console.WriteLine($"Main Thread: {i}"); Thread.Sleep(1000); // Sleep for 1 second } // Wait for the other thread to complete thread.Join(); Console.WriteLine("Main Thread: Counting numbers completed."); } static void CountNumbers() { for (int i = 1; i <= 5; i++) { Console.WriteLine($"Other Thread: {i}"); Thread.Sleep(1500); // Sleep for 1.5 seconds } Console.WriteLine("Other Thread: Counting numbers completed."); } }
In this example, we create a new thread thread
and start it. The CountNumbers
method is executed in the new thread. Meanwhile, in the main thread, we perform some other tasks and use Thread.Sleep()
to introduce a delay of 1 second between each iteration of the loop. This causes the main thread to print its numbers with a 1-second delay.
In the CountNumbers
method, we also introduce a delay of 1.5 seconds between each iteration using Thread.Sleep()
. The output will show the numbers printed by the main thread and the other thread interleaved, but with different delays due to the varying sleep times.
The Join()
method is called on the thread
object to wait for it to complete before proceeding. Once the other thread finishes executing, the main thread prints a completion message.
This example demonstrates how to use the Sleep()
method to control the timing and introduce delays in separate threads.