C# Reference ยท Async and Concurrency
Task.Run() method
Reference for Task.Run in C#: queue CPU-bound work on the thread pool, return results, unwrap async lambdas, pass cancellation tokens and avoid misuse.
Task.Run queues a delegate to the thread pool and returns a task that represents it. It is the standard way to move CPU-bound work off the calling thread, for example so a UI stays responsive or so several computations overlap.
It does not make I/O faster, and it is not needed to call an operation that is already asynchronous. Wrapping await Stream.ReadAsync(...) in Task.Run only adds a thread hop.
int total = await Task.Run(() => ExpensiveSum(data));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static Task Run(Action action); public static Task Run(Action action, CancellationToken cancellationToken); public static Task<TResult> Run<TResult>(Func<TResult> function); public static Task Run(Func<Task> function); public static Task<TResult> Run<TResult>(Func<Task<TResult>> function);
| Parameter | Description |
|---|---|
action / function |
The work to run. A function that returns a Task is unwrapped, so the returned task completes when the inner task does. |
cancellationToken |
Prevents a queued delegate from starting. It does not interrupt code that is already running. |
Returns: a task for the queued work, with the delegate's return value for the generic overloads.
Errors: an exception in the delegate is stored in the task. ArgumentNullException if the delegate is null. A token cancelled before the task starts gives a canceled task.
Usage notes
- Use it for CPU-bound work, not I/O. Asynchronous I/O needs no extra thread; use the library's
...Asyncmethod. - Do not offload in libraries "just in case". Fake-async wrappers such as
Task.Run(() => Compute())hide the cost from callers. Let the caller decide. - Web servers. In ASP.NET Core requests already run on pool threads, so
Task.Runnormally adds overhead rather than parallelism. - Pool limits. The pool starts with about one thread per core and grows slowly. Long blocking work (
Thread.Sleep, blocking waits) can starve it. UseTaskCreationOptions.LongRunningwithTask.Factory.StartNewor a dedicatedThreadfor work that runs for minutes. - Closures. The delegate captures variables, not copies. Changing a loop variable after queueing can surprise you; copy it first.
Task.Factory.StartNewdiffers: with an async lambda it returnsTask<Task>and usesTaskScheduler.Current. PreferTask.Rununless you need its options.- Cancel cooperatively. Check the token inside the delegate (
ThrowIfCancellationRequested) or the work keeps going.