1

NOTE: I am a noob at coding.

I am trying to make a certain task in my application run after a certain amount of time one (for example) I want Console.WriteLine("Hello delay"); to run 180 seconds after Console.WriteLine("Hello World!"); is run, how would I do that?

I have not tried anything else yet.

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // I want (Console.WriteLine("Hello delay");) to run 
            // 180 seconds after (Console.WriteLine("Hello World!");) is run
            Console.WriteLine("Hello delay");
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user15593957
  • 46
  • 1
  • 7
  • Question has already been answered [here](https://stackoverflow.com/questions/20082221/when-to-use-task-delay-when-to-use-thread-sleep) – mr.coffee Jun 17 '21 at 00:23
  • Does this answer your question? [How to add a delay for a 2 or 3 seconds](https://stackoverflow.com/questions/5449956/how-to-add-a-delay-for-a-2-or-3-seconds) – bg117 Jun 17 '21 at 02:37

5 Answers5

3

you can sleep current thread.

using System;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Thread.Sleep(180 * 1000);
            Console.WriteLine("Hello delay");
        }
    }
}
MrMoeinM
  • 2,080
  • 1
  • 11
  • 16
2

Use Task.Run() to run a task and wait for its completion.

static void Main(string[] args)
{
    Console.WriteLine("Hello World!");

    var numSecondsDelay = 180;

    var t = Task.Run(async delegate
    {
        await Task.Delay(numSecondsDelay*1000);
        return numSecondsDelay;
    });
    t.Wait();

    Console.WriteLine("Hello delay");
}
Andrew Halil
  • 1,195
  • 15
  • 15
  • 21
1
using System;
using System.Threading; // add this
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Thread.Sleep(180000); // add this
            Console.WriteLine("Hello delay");
        }
    }
}
Ajeet Kumar
  • 687
  • 6
  • 12
0

like this:

static async void Main(string[] args)
{
    Console.WriteLine("Hello World!");
    
    await Task.Run(() =>
        {
            Thread.Sleep(1000);
            Console.WriteLine("Hello delay");
        });
        
    Console.WriteLine("Hello delay");
}
CorrieJanse
  • 2,374
  • 1
  • 6
  • 23
0

You can use the following code to delay processing for 180 seconds.

System.Threading.Thread.Sleep(180 * 1000);
TidyDev
  • 3,470
  • 9
  • 29
  • 51
bg117
  • 354
  • 4
  • 13