C# Interview Question #63
What is Task and Task<T> in C#?
Async/Await, Tasks & Multithreading Mid-Level Intermediate
Quick Interview Answer
Task represents an asynchronous operation that does not produce a result value. Task<T> represents an asynchronous operation that eventually produces a value of type T.
Detailed Explanation
Task represents an asynchronous operation that does not produce a result value. Task<T> represents an asynchronous operation that eventually produces a value of type T.
A Task can be running, completed successfully, faulted, or canceled. Exceptions from asynchronous operations are normally observed when the task is awaited.
In application code, Task and Task<T> are the standard return types for asynchronous service and repository methods.
Code Example
public async Task SaveAsync()
{
await _context.SaveChangesAsync();
}
public async Task<Product?> GetAsync(int id)
{
return await _context.Products.FindAsync(id);
}