MediumConcept

What is the difference between Task and Thread, and how does async/await work in C#?

Technology:
C#
Experience:
Mid-level,
Senior

Quick answer

A Thread is an operating-system execution unit, while a Task represents an asynchronous operation scheduled on the thread pool; await releases the current thread while the operation is pending and resumes the method when it completes.

Detailed explanation

Creating threads is expensive and you must manage them yourself. A Task is a higher-level abstraction: it can represent CPU work queued to the thread pool (Task.Run) or I/O that does not need a thread at all while waiting, such as an HTTP call or database query.

When the compiler sees await, it turns the method into a state machine. If the awaited task is not finished, the method returns control to its caller and the thread is free to serve other requests. When the task completes, the rest of the method continues, possibly on another thread. This is why async I/O lets a web server handle many more concurrent requests with the same number of threads. async/await is about scalability for I/O-bound work; for CPU-bound work it does not make anything faster by itself.

Example

csharp
public async Task<string> GetPageAsync(HttpClient client, string url)
{
    // thread is released while waiting on the network
    string html = await client.GetStringAsync(url);
    return html.ToUpperInvariant();
}

// run independent calls concurrently
var results = await Task.WhenAll(GetPageAsync(c, a), GetPageAsync(c, b));

Key points

  • Task = promise of work, not a thread
  • await frees the thread during I/O
  • Use Task.WhenAll for independent operations
  • C#Hard

    How do you avoid deadlocks with async/await in C#?

    Use async all the way down instead of blocking on tasks with .Result or .Wait(), and in library code use ConfigureAwait(false) so continuations do not need to return to a captured context.

    Senior 路 Asynchronous Programming
  • C#Easy

    What is the difference between const and readonly in C#?

    A const is a compile-time constant that must be assigned where it is declared, while a readonly field can be assigned at declaration or in the constructor, so its value can be decided at runtime.

    Junior 路 Mid-level 路 Programming Fundamentals
  • C#Medium

    What is LINQ in C# and what is deferred execution?

    LINQ (Language Integrated Query) lets you query collections, databases and XML with a consistent syntax, and deferred execution means a query does not run when you define it but when you enumerate the results.

    Junior 路 Mid-level 路 Functions & Scope