Task
A Task is a promise that some work will finish later, like a pager that buzzes when your table is ready. It represents a job running in the background that gives no result.
In this page:
Syntax
static async Task MethodNameAsync()
{
await Task.Delay(milliseconds);
}
Task task = MethodNameAsync();
await task;
Task
Task represents an asynchronous operation that doesn't produce a value, similar to how void methods don't return one synchronously.
You can await a Task to know when it finishes, or use Task.Run to offload CPU-bound work to a background thread. Tasks can be composed with Task.WhenAll and Task.WhenAny.
Note:
Task.Run(() => ...)is for CPU-bound workawaitalone is enough for naturally asynchronous I/O.
Example: Task
using System;
using System.Threading.Tasks;
class Program
{
static async Task DoWorkAsync()
{
await Task.Delay(50);
Console.WriteLine("Work done");
}
static async Task Main(string[] args)
{
Task t1 = DoWorkAsync();
Task t2 = DoWorkAsync();
await Task.WhenAll(t1, t2);
Console.WriteLine("Both tasks finished");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting to
awaita Task, so exceptions are lost and work is not finished. - Using
Task.Runfor I/O work when async APIs exist. - Using
Thread.Sleepin async code instead ofawait Task.Delay.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: