Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to schedule the execution of a function in 5 seconds with C#

3 Answers

0 votes
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Waiting for 5 seconds...");
        await Task.Delay(5000); // Wait for 5 seconds
        ExecuteFunction();
    }

    static void ExecuteFunction()
    {
        Console.WriteLine("Function executed after 5 seconds!");
    }
}


/*
run:

Waiting for 5 seconds...
Function executed after 5 seconds!

*/

 



answered Jun 24, 2025 by avibootz
0 votes
using System;
using System.Timers;

class Program
{
    static void Main(string[] args)
    {
        Timer timer = new Timer(5000); // Set timer for 5 seconds
        timer.Elapsed += (sender, e) => ExecuteFunction(timer);
        timer.AutoReset = false; // Ensure it only runs once
        timer.Start();

        Console.WriteLine("Timer started. Waiting for 5 seconds...");
        Console.ReadLine(); // Keep the application running
    }

    static void ExecuteFunction(Timer timer) {
        timer.Stop();
        Console.WriteLine("Function executed after 5 seconds!");
    }
}



/*
run:

Timer started. Waiting for 5 seconds...
Function executed after 5 seconds!

*/

 



answered Jun 24, 2025 by avibootz
0 votes
using System;
using System.Threading;

class Program
{
    public static void ExecuteFunction() {
        Console.WriteLine("Function executed!");
    }

    public static void Main()
    {
        Console.WriteLine("Execution paused for 5 seconds...");

        Thread.Sleep(5000); // Pause for 5 seconds

        ExecuteFunction();
    }
}



/*
run:

Execution paused for 5 seconds...
Function executed!

*/

 



answered Jun 24, 2025 by avibootz

Related questions

...