Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. Task.Run() / Task.Delay()

Task.Run() / Task.Delay()

Static methods for running tasks in the background or waiting asynchronously for a specified duration. This page also covers WhenAll() and WhenAny() for running multiple tasks in parallel.

Syntax

using System.Threading.Tasks;

// Runs a delegate on a background thread.
Task task = Task.Run(() => process);
Task<T> task = Task.Run(() => processWithReturnValue);

// Waits asynchronously for the specified number of milliseconds.
await Task.Delay(milliseconds);

// Waits until all tasks have completed.
await Task.WhenAll(task1, task2, task3);

// Waits until the first task completes.
Task first = await Task.WhenAny(task1, task2, task3);

Method List

MethodDescription
Task.Run(action)Runs a delegate on the thread pool and returns a Task representing its completion.
Task.Delay(ms)Returns a Task that completes after the specified number of milliseconds. Does not block the thread.
Task.WhenAll(tasks)Waits asynchronously until all of the provided tasks have completed.
Task.WhenAny(tasks)Returns the first task to complete. Useful for implementing timeouts.
Task.CompletedTaskReturns an already-completed Task. Used as a return value when a method completes synchronously.
task.Wait()Blocks the current thread until the task completes.
task.ResultSynchronously retrieves the result of the task, blocking until it completes.

Sample Code

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

// Run a background task with Task.Run.
Task<int> bgTask = Task.Run(() =>
{
    int sum = 0;
    for (int i = 1; i <= 100; i++) sum += i;
    return sum;
});
Console.WriteLine(await bgTask); // 5050

// Use Task.Delay to sleep asynchronously (alternative to Thread.Sleep).
Console.WriteLine("Start");
await Task.Delay(1000); // Wait 1 second
Console.WriteLine("1 second later");

// WhenAll: run multiple tasks in parallel and wait for all to complete.
Task<string> t1 = Task.Run(async () => { await Task.Delay(100); return "Task 1"; });
Task<string> t2 = Task.Run(async () => { await Task.Delay(200); return "Task 2"; });
Task<string> t3 = Task.Run(async () => { await Task.Delay(50);  return "Task 3"; });

string[] results = await Task.WhenAll(t1, t2, t3);
Console.WriteLine(string.Join(", ", results)); // Task 1, Task 2, Task 3

// WhenAny: get the first task to complete (timeout example).
Task<int> longTask = Task.Run(async () => { await Task.Delay(5000); return 42; });
Task timeoutTask = Task.Delay(1000);

Task finished = await Task.WhenAny(longTask, timeoutTask);
if (finished == timeoutTask)
    Console.WriteLine("Timed out");
else
    Console.WriteLine($"Done: {longTask.Result}");

Notes

Task.WhenAll() runs multiple asynchronous operations in parallel and waits for all of them to finish. This reduces total wait time compared to awaiting each task sequentially.

Using task.Result or task.Wait() inside an async method can cause a deadlock. Always use await inside asynchronous code. If you need to retrieve a result synchronously, consider using Task.FromResult().

For the basic async syntax, see async / await. For cancellation in async operations, see CancellationToken.

If you find any errors or copyright issues, please .