C# - How to Pause a Thread?

Learn, how to pause a thread in C#? By Nidhi Last updated : March 29, 2023

Pausing a thread

To pause a thread, we need to use Thread.Sleep() method, this method takes an argument in milliseconds to pause the thread.

C# program to pause a thread

/*
 * Program to Pause a Thread in C#
 */

using System;
using System.Threading;

class Program {
  static void Main() {
    int loop = 0;
    
    for (loop = 1; loop <= 4; loop++) {
      Console.WriteLine("Sleep Main thread for 1 Second");
      Thread.Sleep(1000);
    }

    Console.WriteLine("Main thread Finished");
  }
}

Output

Sleep Main thread for 1 Second
Sleep Main thread for 1 Second
Sleep Main thread for 1 Second
Sleep Main thread for 1 Second
Main thread Finished
Press any key to continue . . .

Explanation

In the above program, we created a program class that contains a Main() method. In the Main() method, we created a for loop that will execute 4 times, here we used Thread.Sleep() method that will pause or sleep the Main thread for 1 second when Thread.Sleep() method gets called.

C# Thread Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.