.NET by Patrik

Task.Delay (async/await)

The Task.Delay Method creates a task that will complete after a time delay.

  • Task.Delay is generally preferred when working with asynchronous programming using async and await.
  • It returns a Task that represents a time delay.
  • It doesn't block the calling thread. Instead, it allows the thread to be released and continue with other work while waiting for the specified time to elapse.
  • It's more suitable for scenarios where you want to introduce a delay without blocking the execution of the current method or freezing the user interface in GUI applications.

Example:

async Task MyMethod()
{
    // Do something before the delay
    await Task.Delay(1000); // Delay for 1000 milliseconds (1 second)
    // Do something after the delay
}

Comments