How can I perform a short delay in C# without using sleep?

user2706003 picture user2706003 · Aug 22, 2013 · Viewed 177.7k times · Source

I'm incredibly new to programming, and I've been learning well enough so far, I think, but I still can't get a grasp around the idea of making a delay the way I want. What I'm working on is a sort of test "game" thingy using a Windows forms application that involves a combat system. In it, I want to make an NPC that does an action every couple of seconds. The problem is, I also want to allow the player to interact between attacks. Thread.sleep really doesn't seem to work for me not only because I don't know how to multithread, but whenever I try to run it, say, like this:

 textBox1.Text += "\r\nThread Sleeps!";
 System.Threading.Thread.Sleep(4000);
 textBox1.Text += "\r\nThread awakens!";

It seems to insist on sleeping first, then printing both lines.

I think that's all I can say at the moment, but if that's still too vague or wordy, feel free to tell me.

In short, In C# I want to make something delay before running but at the same time still allow user interaction.

Answer

Ohlin picture Ohlin · Aug 22, 2013

If you're using .NET 4.5 you can use the new async/await framework to sleep without locking the thread.

How it works is that you mark the function in need of asynchronous operations, with the async keyword. This is just a hint to the compiler. Then you use the await keyword on the line where you want your code to run asynchronously and your program will wait without locking the thread or the UI. The method you call (on the await line) has to be marked with an async keyword as well and is usually named ending with Async, as in ImportFilesAsync.

What you need to do in your example is:

  1. Make sure your program has .Net Framework 4.5 as Target Framework
  2. Mark your function that needs to sleep with the async keyword (see example below)
  3. Add using System.Threading.Tasks; to your code.

Your code is now ready to use the Task.Delay method instead of the System.Threading.Thread.Sleep method (it is possible to use await on Task.Delay because Task.Delay is marked with async in its definition).

private async void button1_Click(object sender, EventArgs e)
{
    textBox1.Text += "\r\nThread Sleeps!";
    await Task.Delay(3000);
    textBox1.Text += "\r\nThread awakens!";
}

Here you can read more about Task.Delay and Await.