1

I'm trying to find a way of causing the program to not pause but for their to be a delay to execute certain tasks. I.e. I am trying to delay outputting 'Hello' to the console for 10 seconds for example, but the program will continue to execute the rest of the program.

1
  • You could start another thread which itself pauses for 10 seconds and then writes to the console. Commented Feb 14, 2017 at 20:01

5 Answers 5

5

Using TPL:

static void Main(string[] args)
{
    Console.WriteLine("Starting at " + DateTime.Now.ToString());

    Task.Run(() =>
    {
        Thread.Sleep(10000);
        Console.WriteLine("Done sleeping " + DateTime.Now.ToString());
    });

    Console.WriteLine("Press any Key...");

    Console.ReadKey();

}

output:

Starting at 2/14/2017 3:05:09 PM
Press any Key...
Done sleeping 2/14/2017 3:05:19 PM

just note that if you press a key before 10 seconds, it will exit.

Sign up to request clarification or add additional context in comments.

Comments

2

There are 2 typical ways to simulate a delay:

  • an asynchronous task-like: Task.Delay
  • or a blocking activity: Thread.Sleep

You seem to refer to the first situation.

Here it is an example

    public static void Main(string[] args)
    {
        Both();
    }
    static void Both() {
        var list = new Task [2];
        list[0]  = PauseAndWrite();
        list[1]  =  WriteMore();
        Task.WaitAll(list);
    }
    static async Task PauseAndWrite() {
        await Task.Delay(2000);
        Console.WriteLine("A !");
    }
    static async Task WriteMore() {

        for(int i = 0; i<5; i++) {
            await Task.Delay(500);
            Console.WriteLine("B - " + i);
        }
    }

Output

B - 0
B - 1
B - 2
A !
B - 3
B - 4

Comments

1

Start a new thread:

Task.Factory.StartNew(new Action(() =>
{
    Thread.Sleep(1000 * 10); // sleep for 10 seconds
    Console.Write("Whatever");
}));

Comments

1

You could use a combination of Task.Delay and ContinueWith methods:

Task.Delay(10000).ContinueWith(_ => Console.WriteLine("Done"));

Comments

0

You could use 'Thread.Sleep(10000);'

See: https://msdn.microsoft.com/en-us/library/d00bd51t(v=vs.110).aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.