Task<T>
A Task of T is a promise that comes with a gift: when the background job finishes, you get an answer of type T. It is like ordering food and getting the meal when it is ready.
In this page:
Syntax
static async Task<type> MethodNameAsync()
{
await Task.Delay(milliseconds);
return value;
}
type result = await MethodNameAsync();
Task<T>
Task<T> is an asynchronous operation that eventually produces a result of type T. Awaiting it gives you the T value directly once the task completes. It's the asynchronous equivalent of a method with a non-void return type.
Note:
The
.Result property on Task<T> blocks synchronously — prefer await to avoid deadlocks.Example: Task<T>
using System;
using System.Threading.Tasks;
class Program
{
static async Task<int> SumAsync(int a, int b)
{
await Task.Delay(50);
return a + b;
}
static async Task Main(string[] args)
{
int result = await SumAsync(4, 5);
Console.WriteLine(result);
}
}
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
- Reading
.Resultbefore the task completes, which blocks the thread. - Forgetting that an
asyncmethod returningTask<T>returnsT, notTask<T>. - Not handling exceptions from the awaited task.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: