C# Wait For Seconds (How it Works for Developers)

C# wait statement is a popular feature in programming when you need to pause the execution of your program for a specified duration. In this tutorial, we'll cover everything you need to know about wait statements, including async methods, the sleep command, sleep function, and console apps. We'll use a storytelling approach and real-life examples to keep things engaging and easy to understand. So, let's get started!

The Sleep Command

The sleep command is a simple yet powerful tool that allows you to pause the execution of your code for a specific amount of time. It's like telling your program to take a short nap before moving on to the next task. In C#, you can use the Thread.Sleep(int milliseconds) method to achieve this.

Here's an example of how you might use the sleep command in a console application:


    using System;
    using System.Threading;

    class Program
    {
        public static void Main()
        {
            Console.WriteLine("Starting the program...");
            Thread.Sleep(3000); // Sleep for 3 seconds
            Console.WriteLine("...Program continues after 3 seconds");
        }
    }

    using System;
    using System.Threading;

    class Program
    {
        public static void Main()
        {
            Console.WriteLine("Starting the program...");
            Thread.Sleep(3000); // Sleep for 3 seconds
            Console.WriteLine("...Program continues after 3 seconds");
        }
    }
Imports System
	Imports System.Threading

	Friend Class Program
		Public Shared Sub Main()
			Console.WriteLine("Starting the program...")
			Thread.Sleep(3000) ' Sleep for 3 seconds
			Console.WriteLine("...Program continues after 3 seconds")
		End Sub
	End Class
VB   C#

In the above example, the program starts by printing "Starting the program..." to the console. Then, it uses the Thread.Sleep method to pause for 3,000 milliseconds, or three seconds. After the specified delay, the program resumes and prints the output "...Program continues after 3 seconds" to the console.

Async Method and Tasks

Async methods in C# enable you to execute multiple tasks concurrently without blocking the main thread. This means that while one task is waiting, other tasks can continue running. To implement an async method, you'll need to use the async keyword and the Task class.

Consider the following example:

using System;
using System.Threading.Tasks;

class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Starting Task 1...");
        var task1 = DoSomethingAsync(3000);
        Console.WriteLine("Starting Task 2...");
        var task2 = DoSomethingAsync(2000);

        await Task.WhenAll(task1, task2);
        Console.WriteLine("Both tasks completed.");
    }

    private static async Task DoSomethingAsync(int milliseconds)
    {
        await Task.Delay(milliseconds);
        Console.WriteLine($"Task completed after {milliseconds} milliseconds");
    }
}
using System;
using System.Threading.Tasks;

class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Starting Task 1...");
        var task1 = DoSomethingAsync(3000);
        Console.WriteLine("Starting Task 2...");
        var task2 = DoSomethingAsync(2000);

        await Task.WhenAll(task1, task2);
        Console.WriteLine("Both tasks completed.");
    }

    private static async Task DoSomethingAsync(int milliseconds)
    {
        await Task.Delay(milliseconds);
        Console.WriteLine($"Task completed after {milliseconds} milliseconds");
    }
}
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Public Shared Async Function Main() As Task
		Console.WriteLine("Starting Task 1...")
		Dim task1 = DoSomethingAsync(3000)
		Console.WriteLine("Starting Task 2...")
		Dim task2 = DoSomethingAsync(2000)

		Await Task.WhenAll(task1, task2)
		Console.WriteLine("Both tasks completed.")
	End Function

	Private Shared Async Function DoSomethingAsync(ByVal milliseconds As Integer) As Task
		Await Task.Delay(milliseconds)
		Console.WriteLine($"Task completed after {milliseconds} milliseconds")
	End Function
End Class
VB   C#

In this code example, we have two tasks that run concurrently. The DoSomethingAsync method takes an int parameter, which represents the time in milliseconds that the task should be delayed. The Task.Delay method is similar to the Thread.Sleep() method, but it works with async tasks and doesn't block the main thread.

Using Timers Schedule Your Tasks

Timers in C# allow you to execute a specific task at a specified interval. You can create a timer using the System.Timers.Timer class. Here's an example of how to use a timer in a console app

using System;
using System.Timers;

class Program
{
    public static void Main()
    {
        var timer = new Timer(1000); // Create a timer with a 1-second interval
        timer.Elapsed += OnTimerElapsed;
        timer.AutoReset = true;
        timer.Enabled = true;

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }

    private static void OnTimerElapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Timer ticked at " + e.SignalTime);
    }
}
using System;
using System.Timers;

class Program
{
    public static void Main()
    {
        var timer = new Timer(1000); // Create a timer with a 1-second interval
        timer.Elapsed += OnTimerElapsed;
        timer.AutoReset = true;
        timer.Enabled = true;

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }

    private static void OnTimerElapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Timer ticked at " + e.SignalTime);
    }
}
Imports System
Imports System.Timers

Friend Class Program
	Public Shared Sub Main()
		Dim timer As New Timer(1000) ' Create a timer with a 1-second interval
		AddHandler timer.Elapsed, AddressOf OnTimerElapsed
		timer.AutoReset = True
		timer.Enabled = True

		Console.WriteLine("Press any key to exit...")
		Console.ReadKey()
	End Sub

	Private Shared Sub OnTimerElapsed(ByVal sender As Object, ByVal e As ElapsedEventArgs)
		Console.WriteLine("Timer ticked at " & e.SignalTime)
	End Sub
End Class
VB   C#

In the above example, we create a timer with a 1-second interval. The OnTimerElapsed method is executed every time the timer ticks. We set the AutoReset property to true so that the timer restarts automatically after each tick. The Enabled property is set to true to start the timer.

When you run this console application, you'll see the timer ticking every second, printing the tick time to the console. The program will continue running until you press any key to exit.

Creating Custom Wait Functions

Sometimes, you might need a custom wait function to meet specific requirements in your code. For instance, you might want to create a wait function that only blocks the current task, rather than the entire thread. You can achieve this using async delegates.

Here's an example of a custom wait function:

using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Starting Task 1...");
        await CustomWaitAsync(3000);
        Console.WriteLine("Task 1 completed.");

        Console.WriteLine("Starting Task 2...");
        await CustomWaitAsync(2000);
        Console.WriteLine("Task 2 completed.");
    }

    private static async Task CustomWaitAsync(int milliseconds)
    {
        await Task.Run(() => Thread.Sleep(milliseconds));
    }
}
using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Starting Task 1...");
        await CustomWaitAsync(3000);
        Console.WriteLine("Task 1 completed.");

        Console.WriteLine("Starting Task 2...");
        await CustomWaitAsync(2000);
        Console.WriteLine("Task 2 completed.");
    }

    private static async Task CustomWaitAsync(int milliseconds)
    {
        await Task.Run(() => Thread.Sleep(milliseconds));
    }
}
Imports System
Imports System.Threading
Imports System.Threading.Tasks

Friend Class Program
	Public Shared Async Function Main() As Task
		Console.WriteLine("Starting Task 1...")
		Await CustomWaitAsync(3000)
		Console.WriteLine("Task 1 completed.")

		Console.WriteLine("Starting Task 2...")
		Await CustomWaitAsync(2000)
		Console.WriteLine("Task 2 completed.")
	End Function

	Private Shared Async Function CustomWaitAsync(ByVal milliseconds As Integer) As Task
		Await Task.Run(Sub() Thread.Sleep(milliseconds))
	End Function
End Class
VB   C#

In this code example, the CustomWaitAsync method accepts an int parameter representing the delay time in milliseconds. The method uses an async delegate to run the Thread.Sleep function within a new task, ensuring that the current task is blocked while waiting, but not the main thread.

Choosing the Right Wait Strategy

Now that we've covered the C# wait statement, sleep command, async methods, timers, and custom wait functions, it's essential to know when to use each technique. Here's a quick summary

  • Use the Thread.Sleep function when you need a simple way to pause the execution of your code for a specified amount of time.
  • Use async methods and tasks when you need to execute multiple tasks concurrently without blocking the main thread.
  • Use timers when you need to execute a specific task at a specified interval.
  • Create custom wait functions when you have specific requirements that aren't met by the built-in methods.

Generating PDFs with IronPDF using Wait function

IronPDF is a powerful C# library that allows you to create, edit, and extract content from PDF files in your .NET applications. It can seamlessly integrate with your wait strategies to generate PDF documents after executing tasks or during scheduled intervals.

For instance, you can use IronPDF in combination with an async method to generate a PDF report after fetching data from a database without blocking the main thread. Similarly, you can use a timer to create a PDF snapshot of your application's data at regular intervals.

To get started with IronPDF, you need to install the NuGet package:

:PackageInstall

Here's an example of how you can use IronPDF with a wait function:

using System;
using System.Threading.Tasks;
using System.Diagnostics;
using IronPdf;

class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Starting the PDF generation task...");
    Stopwatch stopwatch = Stopwatch.StartNew();
        await Task.Delay(3000); // Wait for 3 seconds
        GeneratePdf();
        Console.WriteLine("PDF generated successfully.");
    }

    private static void GeneratePdf()
    {
        var htmlToPdf = new ChromePdfRenderer();
        var pdf = htmlToPdf.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        pdf.SaveAs("HelloWorld.pdf");
    }
}
using System;
using System.Threading.Tasks;
using System.Diagnostics;
using IronPdf;

class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Starting the PDF generation task...");
    Stopwatch stopwatch = Stopwatch.StartNew();
        await Task.Delay(3000); // Wait for 3 seconds
        GeneratePdf();
        Console.WriteLine("PDF generated successfully.");
    }

    private static void GeneratePdf()
    {
        var htmlToPdf = new ChromePdfRenderer();
        var pdf = htmlToPdf.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        pdf.SaveAs("HelloWorld.pdf");
    }
}
Imports System
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports IronPdf

Friend Class Program
	Public Shared Async Function Main() As Task
		Console.WriteLine("Starting the PDF generation task...")
	Dim stopwatch As Stopwatch = System.Diagnostics.Stopwatch.StartNew()
		Await Task.Delay(3000) ' Wait for 3 seconds
		GeneratePdf()
		Console.WriteLine("PDF generated successfully.")
	End Function

	Private Shared Sub GeneratePdf()
		Dim htmlToPdf = New ChromePdfRenderer()
		Dim pdf = htmlToPdf.RenderHtmlAsPdf("<h1>Hello, World!</h1>")
		pdf.SaveAs("HelloWorld.pdf")
	End Sub
End Class
VB   C#

In this code example, we use the Task.Delay method to wait for 3 seconds before generating a PDF. The PDF is then saved as "HelloWorld.pdf" in the application's working directory.

OUTPUT

C# Wait For Seconds (How It Works For Developers) Figure 1

In C# applications, you can efficiently use sleep function to manage current thread and CPU time while performing operations such as loading data into a DataTable or generating PDF reports using IronPDF.

Conclusion

In conclusion, understanding and implementing C# wait statements, sleep commands, async methods, timers, and custom wait functions is crucial to manage your applications efficiently.

By incorporating IronPDF, you can take your applications to the next level by creating PDF documents on-the-fly, without blocking the main thread.

IronPDF offers a free trial, allowing you to explore its extensive capabilities without any commitment. If you decide to continue using IronPDF after the trial period, licensing starts at $749.