Introduction

If you build applications with C# and .NET, you have already run into async, await, Task and CancellationToken scattered all over the code β€” especially in ASP.NET Core APIs. But do you really understand what happens when you mark a method as async? And more importantly: is asynchronous programming the same thing as parallelism? The short answer is no, and confusing these two concepts is one of the most common mistakes among developers.

In this article, I demystify asynchronous programming in C# in a practical, hands-on way. You will understand the fundamental difference between asynchronous and parallel code, how threads work (including what it means to be thread-safe), the real benefits of using async/await correctly, and why CancellationToken is essential for building responsive, resilient applications β€” including in ASP.NET Core controllers. By the end, you will have complete examples you can copy, paste and run to feel the difference between synchronous and asynchronous in practice.

This content is aimed at back-end and full-stack developers who work with .NET and want to write correct, performant and safe asynchronous code. If you already master API security concepts, such as Authentication & Authorization: JWT, OAuth2, OpenID Connect, or use automation in your daily work as described in Makefile: Automating tasks for Python, Hugo and Docker, understanding asynchronous programming will raise the quality of your code even further.

πŸ“¦ Source code: The complete implementation for this article is in the blog-zocateli-sample repository on GitHub. Clone it, explore it and adapt it to your context.


Asynchronous Is Not Parallelism

This is the most important point of this article, and it needs to be clear from the start: asynchronous programming and parallelism are different concepts. Many developers use the terms as synonyms, but they solve different problems.

What Is Asynchronous Programming?

Asynchronous programming is about not blocking the current thread while waiting for a slow operation to finish. When you make an HTTP call, read a file from disk or query a database, those operations involve I/O (input/output) β€” and the processor sits idle waiting for the response. With asynchronous code, the thread is released to do other things while the I/O operation happens.

What Is Parallelism?

Parallelism is about running multiple tasks simultaneously, using multiple processor cores. It is useful for CPU-bound operations β€” tasks that really need heavy processing, such as mathematical calculations, image compression or data processing.

The Restaurant Analogy

Imagine a restaurant with one waiter (the thread):

  • Synchronous: The waiter takes a table’s order, goes to the kitchen, stands still waiting for the dish to be ready, comes back and delivers it. Only then does he serve the next table. If the dish takes 20 minutes, the waiter stands still for 20 minutes.
  • Asynchronous: The waiter takes the order, hands it to the kitchen and goes to serve other tables while the dish is being prepared. When the dish is ready, he picks it up and delivers it. A single waiter serves several tables.
  • Parallel: The restaurant hires several waiters (several threads) to serve tables at the same time. Each waiter works independently.

Illustration comparing a single waiter serving several tables (asynchronous) with several waiters working at the same time (parallel)

ℹ️ Info: Asynchronous is about efficiency β€” doing more with fewer resources. Parallelism is about speed β€” doing more things at the same time using more resources. In web APIs, asynchronous is almost always what you want; parallelism is for specific heavy-processing scenarios.

Direct Comparison

AspectAsynchronousParallel
Problem it solvesI/O operations (network, disk, database)Heavy processing (CPU)
ThreadsReleases the thread while waitingUses multiple threads simultaneously
Main featureasync/await, TaskParallel.ForEach, Task.Run, PLINQ
ExampleHTTP call, file readHash calculation, image compression
When to useWeb APIs, I/O-boundBatch processing, CPU-bound

How Threads Work in C#

To understand asynchronous programming, it is fundamental to understand what threads are and how .NET manages them.

What Is a Thread?

A thread is the smallest unit of execution of a program. When your .NET application starts, it gets at least one thread β€” the main thread. Each thread has its own execution stack, but all of them share the same memory space (heap) of the process.

.NET uses the ThreadPool β€” a managed pool of reusable threads. Instead of constantly creating and destroying threads (which is expensive), the runtime keeps a set of threads ready for use. When an asynchronous operation completes, a pool thread is assigned to continue the execution.

Thread-Safe vs Thread-Unsafe

When multiple threads access the same shared resource (a variable, list, dictionary), race conditions can occur β€” situations where the result depends on the order in which threads execute, which is unpredictable.

Thread-Unsafe Example (Race Condition)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// ❌ PROBLEM: This code is NOT thread-safe
// Multiple asynchronous continuations access the same variable without protection

var contador = 0;

// Asynchronous method that modifies shared state
async Task IncrementarSemProtecaoAsync()
{
    await Task.Yield(); // Forces the continuation onto another pool thread
    contador++;         // ❌ Race condition: not an atomic operation
}

// Fires 1000 concurrent asynchronous calls
var tasks = Enumerable.Range(0, 1000)
    .Select(_ => IncrementarSemProtecaoAsync());

await Task.WhenAll(tasks);

Console.WriteLine($"Expected: 1000, Got: {contador}");
// Output may be: Expected: 1000, Got: 987 (or another value < 1000)

The contador++ looks like a simple operation, but internally it is three steps: read the value, add 1, write the new value. If two threads read the value 500 at the same time, both write 501, and one increment is lost. This happens because contador++ is not an atomic operation.

Thread-Safe Example (with lock)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// βœ… CORRECT: Access protected with lock
var contador = 0;
var lockObj = new object();

async Task IncrementarComLockAsync()
{
    await Task.Yield();
    lock (lockObj)
    {
        contador++; // Only one thread at a time runs this block
    }
}

var tasks = Enumerable.Range(0, 1000)
    .Select(_ => IncrementarComLockAsync());

await Task.WhenAll(tasks);

Console.WriteLine($"Expected: 1000, Got: {contador}");
// Output: Expected: 1000, Got: 1000 βœ…

What Are Atomic Operations?

An atomic operation is an operation that either completes entirely or does not happen at all β€” there is no middle ground. From the point of view of other threads, the operation is instantaneous: no thread can observe the intermediate state.

The problem with contador++ is that it is not atomic. It is three separate operations:

  1. Read the current value of contador from memory.
  2. Add 1 to the value read.
  3. Write the new value back to memory.

Between step 1 and step 3, another thread can read the same old value β€” causing the race condition shown above. An atomic operation guarantees that these three steps happen as if they were a single one, without another thread being able to interfere midway.

.NET offers ready-to-use atomic operations in the Interlocked class, which uses special processor instructions (such as lock cmpxchg on x86) to guarantee atomicity without needing a lock β€” which makes the code faster in high-concurrency scenarios.

OperationInterlocked methodNon-atomic equivalent
IncrementInterlocked.Increment(ref x)x++
DecrementInterlocked.Decrement(ref x)x--
Add valueInterlocked.Add(ref x, valor)x += valor
Swap valueInterlocked.Exchange(ref x, novo)x = novo
Swap if equalInterlocked.CompareExchange(ref x, novo, esperado)if (x == esperado) x = novo

Thread-Safe Example (with Interlocked)

For simple operations such as increment, Interlocked is more efficient than lock because it does not block other threads β€” the operation is atomic at the hardware level:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// βœ… CORRECT and faster: Interlocked for atomic operations
var contador = 0;

async Task IncrementarAtomicoAsync()
{
    await Task.Yield();
    Interlocked.Increment(ref contador); // βœ… Atomic operation β€” no lock
}

var tasks = Enumerable.Range(0, 1000)
    .Select(_ => IncrementarAtomicoAsync());

await Task.WhenAll(tasks);

Console.WriteLine($"Expected: 1000, Got: {contador}");
// Output: Expected: 1000, Got: 1000 βœ…

ℹ️ Info: Use lock when you need to protect a block of code with multiple operations (read + modify + write a complex structure). Use Interlocked when you need to protect a single variable with simple operations (increment, swap). Interlocked is between 10Γ— and 50Γ— faster than lock for these individual operations.

Thread-Safe Collections in .NET

.NET offers collections in the System.Collections.Concurrent namespace designed for safe access by multiple threads:

Thread-Unsafe CollectionThread-Safe EquivalentWhen to use
List<T>ConcurrentBag<T>Unordered collection
Dictionary<K,V>ConcurrentDictionary<K,V>Dictionary with concurrent access
Queue<T>ConcurrentQueue<T>Producer/consumer queue
Stack<T>ConcurrentStack<T>Stack with concurrent access

πŸ’‘ Tip: If you are using pure async/await (without Task.Run or Parallel), in many scenarios you do not need thread-safe collections, because asynchronous code usually runs sequentially in a single context thread. The concern with thread safety arises when you introduce real parallelism.


async/await in Practice: Synchronous vs Asynchronous

Now to what matters: code you can run and feel the difference. Create a console project to test:

1
2
dotnet new console -n AsyncDemo
cd AsyncDemo

Example 1: Synchronous Code (Blocking)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Program.cs β€” SYNCHRONOUS version
using System.Diagnostics;

var sw = Stopwatch.StartNew();

Console.WriteLine("Starting SYNCHRONOUS operations...\n");

// Simulates 3 HTTP calls that take 2 seconds each
var resultado1 = BuscarDadosSincrono("Service A", 2000);
var resultado2 = BuscarDadosSincrono("Service B", 2000);
var resultado3 = BuscarDadosSincrono("Service C", 2000);

Console.WriteLine($"\n{resultado1}");
Console.WriteLine(resultado2);
Console.WriteLine(resultado3);

sw.Stop();
Console.WriteLine($"\n⏱️ Total time: {sw.ElapsedMilliseconds}ms");
// Expected output: ~6000ms (2s + 2s + 2s β€” sequential)

static string BuscarDadosSincrono(string servico, int delayMs)
{
    Console.WriteLine($"  [{DateTime.Now:HH:mm:ss.fff}] Fetching {servico}...");
    Thread.Sleep(delayMs); // ❌ Blocks the thread
    Console.WriteLine($"  [{DateTime.Now:HH:mm:ss.fff}] {servico} done.");
    return $"Data from {servico}";
}

Expected output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Starting SYNCHRONOUS operations...

  [19:00:00.001] Fetching Service A...
  [19:00:02.003] Service A done.
  [19:00:02.004] Fetching Service B...
  [19:00:04.006] Service B done.
  [19:00:04.006] Fetching Service C...
  [19:00:06.008] Service C done.

Data from Service A
Data from Service B
Data from Service C

⏱️ Total time: 6015ms

Example 2: Asynchronous Code (Non-Blocking)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Program.cs β€” ASYNCHRONOUS version
using System.Diagnostics;

var sw = Stopwatch.StartNew();

Console.WriteLine("Starting ASYNCHRONOUS operations...\n");

// Starts all 3 calls at the same time
var task1 = BuscarDadosAsync("Service A", 2000);
var task2 = BuscarDadosAsync("Service B", 2000);
var task3 = BuscarDadosAsync("Service C", 2000);

// Waits for ALL to complete (without blocking the thread)
var resultados = await Task.WhenAll(task1, task2, task3);

Console.WriteLine($"\n{resultados[0]}");
Console.WriteLine(resultados[1]);
Console.WriteLine(resultados[2]);

sw.Stop();
Console.WriteLine($"\n⏱️ Total time: {sw.ElapsedMilliseconds}ms");
// Expected output: ~2000ms (all run "at the same time")

static async Task<string> BuscarDadosAsync(string servico, int delayMs)
{
    Console.WriteLine($"  [{DateTime.Now:HH:mm:ss.fff}] Fetching {servico}...");
    await Task.Delay(delayMs); // βœ… Releases the thread while waiting
    Console.WriteLine($"  [{DateTime.Now:HH:mm:ss.fff}] {servico} done.");
    return $"Data from {servico}";
}

Expected output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Starting ASYNCHRONOUS operations...

  [19:00:00.001] Fetching Service A...
  [19:00:00.002] Fetching Service B...
  [19:00:00.002] Fetching Service C...
  [19:00:02.005] Service A done.
  [19:00:02.005] Service B done.
  [19:00:02.006] Service C done.

Data from Service A
Data from Service B
Data from Service C

⏱️ Total time: 2008ms

⚠️ Warning: Notice the difference: 6 seconds vs 2 seconds. In the asynchronous code, the three I/O operations started almost at the same time. While each one was waiting, the thread was free. This is not parallelism β€” it is a single thread managing multiple I/O operations concurrently. Task.Delay releases the thread; Thread.Sleep blocks it.

What Happens Under the Hood?

When you write await Task.Delay(2000), the C# compiler turns your async method into a state machine. Simplifying:

  1. The code before the await runs normally.
  2. At the await point, if the Task has not completed yet, the thread is returned to the ThreadPool.
  3. When the I/O operation finishes, a pool thread is assigned to continue the execution from where it stopped.
  4. This repeats for each await in the method.

That is why async/await is so powerful in web APIs: while one request waits for the database response, the thread can serve other requests.


CancellationToken: Why and How to Use It

CancellationToken is a .NET mechanism to signal cooperative cancellation of asynchronous operations. Without it, if a user closes the browser, disconnects or the request hits a timeout, your API keeps processing needlessly β€” consuming server resources with nobody to receive the response.

Why Is It Important?

Consider these scenarios:

  1. The user makes a request that takes 30 seconds and closes the browser tab after 5 seconds.
  2. A timeout is hit at the gateway or load balancer.
  3. Your API calls an external service that is slow and you want to impose a time limit.

Without CancellationToken, your code keeps executing the full operation, wasting CPU, memory and database connections β€” resources that could serve other users.

Basic CancellationToken Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Basic CancellationToken demonstration
using var cts = new CancellationTokenSource();

// Cancels automatically after 3 seconds
cts.CancelAfter(TimeSpan.FromSeconds(3));

try
{
    Console.WriteLine("Starting long-running operation...");
    await OperacaoDemoradaAsync(cts.Token);
    Console.WriteLine("Operation completed successfully!");
}
catch (OperationCanceledException)
{
    Console.WriteLine("β›” Operation canceled! Resources released.");
}

static async Task OperacaoDemoradaAsync(CancellationToken cancellationToken)
{
    for (int i = 1; i <= 10; i++)
    {
        // Checks whether cancellation was requested
        cancellationToken.ThrowIfCancellationRequested();

        Console.WriteLine($"  Processing step {i}/10...");
        await Task.Delay(1000, cancellationToken);
    }
}

Expected output:

1
2
3
4
5
Starting long-running operation...
  Processing step 1/10...
  Processing step 2/10...
  Processing step 3/10...
β›” Operation canceled! Resources released.

CancellationToken in Service Methods

Always propagate the CancellationToken through the entire call chain:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Service interface
public interface IProdutoService
{
    Task<List<Produto>> ObterTodosAsync(CancellationToken cancellationToken = default);
    Task<Produto?> ObterPorIdAsync(int id, CancellationToken cancellationToken = default);
}

// Service implementation
public class ProdutoService : IProdutoService
{
    private readonly HttpClient _httpClient;
    private readonly AppDbContext _dbContext;

    public ProdutoService(HttpClient httpClient, AppDbContext dbContext)
    {
        _httpClient = httpClient;
        _dbContext = dbContext;
    }

    public async Task<List<Produto>> ObterTodosAsync(
        CancellationToken cancellationToken = default)
    {
        // Entity Framework accepts CancellationToken natively
        return await _dbContext.Produtos
            .AsNoTracking()
            .ToListAsync(cancellationToken);
    }

    public async Task<Produto?> ObterPorIdAsync(
        int id,
        CancellationToken cancellationToken = default)
    {
        // HttpClient also accepts CancellationToken
        var response = await _httpClient.GetAsync(
            $"/api/produtos/{id}",
            cancellationToken);

        response.EnsureSuccessStatusCode();

        return await response.Content
            .ReadFromJsonAsync<Produto>(cancellationToken: cancellationToken);
    }
}

πŸ’‘ Tip: Use CancellationToken cancellationToken = default as the last parameter. The default for CancellationToken is CancellationToken.None, which means “no cancellation” β€” keeping compatibility with code that does not need cancellation.


CancellationToken in the ASP.NET Core Controller

Using CancellationToken in the controller is one of the best practices for ASP.NET Core APIs, and it makes total sense: the framework already provides a cancellation token automatically when the request is aborted by the client.

How Does It Work?

When you add CancellationToken as a parameter of an action, ASP.NET Core automatically injects a token bound to the HTTP connection. If the client disconnects (closes the tab, timeout, cancels the fetch), the token is signaled as canceled.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ProdutosController : ControllerBase
{
    private readonly IProdutoService _produtoService;

    public ProdutosController(IProdutoService produtoService)
    {
        _produtoService = produtoService;
    }

    // βœ… CancellationToken injected automatically by ASP.NET Core
    [HttpGet]
    public async Task<ActionResult<List<Produto>>> ObterTodos(
        CancellationToken cancellationToken)
    {
        var produtos = await _produtoService
            .ObterTodosAsync(cancellationToken);

        return Ok(produtos);
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<Produto>> ObterPorId(
        int id,
        CancellationToken cancellationToken)
    {
        var produto = await _produtoService
            .ObterPorIdAsync(id, cancellationToken);

        if (produto is null)
            return NotFound();

        return Ok(produto);
    }

    // Endpoint with a long-running operation β€” perfect for CancellationToken
    [HttpPost("relatorio")]
    public async Task<ActionResult<Relatorio>> GerarRelatorio(
        [FromBody] RelatorioRequest request,
        CancellationToken cancellationToken)
    {
        try
        {
            var relatorio = await _produtoService
                .GerarRelatorioAsync(request, cancellationToken);

            return Ok(relatorio);
        }
        catch (OperationCanceledException)
        {
            // Optional log β€” ASP.NET Core already handles this cleanly
            return StatusCode(499, "Request canceled by the client");
        }
    }
}

Complete Chain: Controller β†’ Service β†’ Repository

The real power of CancellationToken shows up when it travels through the entire chain of calls:

1
2
HTTP Client β†’ Controller β†’ Service β†’ Repository β†’ Database
                  ↓ cancellationToken passed along the whole chain ↓
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Repository
public class ProdutoRepository
{
    private readonly AppDbContext _dbContext;

    public ProdutoRepository(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<List<Produto>> ObterComFiltroAsync(
        string? categoria,
        CancellationToken cancellationToken = default)
    {
        var query = _dbContext.Produtos.AsNoTracking();

        if (!string.IsNullOrEmpty(categoria))
            query = query.Where(p => p.Categoria == categoria);

        // If the client disconnects, the database query is canceled
        return await query.ToListAsync(cancellationToken);
    }
}

⚠️ Warning: When a database query is canceled via CancellationToken, Entity Framework sends a cancellation command to the database. This releases the connection and resources on the database server, not only in the application. It is a double win: it releases resources both in the API and in the database.


Complete Example: Testing Synchronous vs Asynchronous

So that you can run it and see the difference in practice, here is a complete example with a minimal API that demonstrates both scenarios:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Program.cs β€” Minimal API demonstrating Synchronous vs Asynchronous
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// SYNCHRONOUS endpoint β€” blocks the thread during the "query"
app.MapGet("/api/sincrono", () =>
{
    var sw = System.Diagnostics.Stopwatch.StartNew();

    // Simulates 3 sequential queries of 1 second each
    Thread.Sleep(1000); // query 1
    Thread.Sleep(1000); // query 2
    Thread.Sleep(1000); // query 3

    sw.Stop();
    return Results.Ok(new
    {
        modo = "synchronous",
        tempoMs = sw.ElapsedMilliseconds,
        mensagem = "Thread was blocked during the whole execution"
    });
});

// ASYNCHRONOUS endpoint β€” releases the thread during the "query"
app.MapGet("/api/assincrono", async (CancellationToken cancellationToken) =>
{
    var sw = System.Diagnostics.Stopwatch.StartNew();

    // Starts 3 asynchronous queries at the same time
    var t1 = Task.Delay(1000, cancellationToken);
    var t2 = Task.Delay(1000, cancellationToken);
    var t3 = Task.Delay(1000, cancellationToken);

    await Task.WhenAll(t1, t2, t3);

    sw.Stop();
    return Results.Ok(new
    {
        modo = "asynchronous",
        tempoMs = sw.ElapsedMilliseconds,
        mensagem = "Thread was released during the waits"
    });
});

// Endpoint that demonstrates CancellationToken
app.MapGet("/api/demorado", async (CancellationToken cancellationToken) =>
{
    var etapas = new List<string>();

    try
    {
        for (int i = 1; i <= 10; i++)
        {
            cancellationToken.ThrowIfCancellationRequested();
            etapas.Add($"Step {i} completed");
            await Task.Delay(1000, cancellationToken);
        }

        return Results.Ok(new
        {
            status = "completed",
            etapas
        });
    }
    catch (OperationCanceledException)
    {
        return Results.Json(new
        {
            status = "canceled",
            etapasCompletadas = etapas,
            mensagem = "Client disconnected. Resources released."
        }, statusCode: 499);
    }
});

app.Run();

To test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Terminal 1: Start the API
dotnet run

# Terminal 2: Test the synchronous endpoint
curl http://localhost:5000/api/sincrono
# Response: { "modo": "synchronous", "tempoMs": 3005, ... }

# Terminal 2: Test the asynchronous endpoint
curl http://localhost:5000/api/assincrono
# Response: { "modo": "asynchronous", "tempoMs": 1003, ... }

# Terminal 2: Test CancellationToken (cancel with Ctrl+C after 3s)
curl http://localhost:5000/api/demorado
# If canceled after 3s: { "status": "canceled", "etapasCompletadas": [...] }

πŸ“ Example: Compare the times: the synchronous endpoint takes ~3 seconds (3 Γ— 1s sequential), while the asynchronous one takes ~1 second (3 Γ— 1s concurrent). The same logic applies to real database queries, HTTP calls and file reads.


Tips and Good Practices

Here are the essential practices for writing correct, performant asynchronous code in C#:

  • Always use async/await for I/O operations. HTTP calls, database queries, file reads/writes β€” all of these operations should be asynchronous. Never use .Result or .Wait() in asynchronous code, because it can cause deadlocks.

  • Prefer await Task.WhenAll() for independent operations. If you need to query three different services that do not depend on each other, start all the tasks and use Task.WhenAll to wait. This can drastically reduce the total response time.

  • Always propagate the CancellationToken. Received a CancellationToken? Pass it to all asynchronous methods in the chain. Entity Framework, HttpClient, Task.Delay β€” all of them accept CancellationToken.

  • Use ConfigureAwait(false) in libraries. If you are writing a library (not an application), use await task.ConfigureAwait(false) to avoid capturing the SynchronizationContext unnecessarily. In ASP.NET Core APIs this is not necessary because there is no SynchronizationContext.

  • Never use async void. The only exception is event handlers. async void methods cannot be awaited and unhandled exceptions can crash the application. Always return Task or Task<T>.

  • Do not use Task.Run to wrap synchronous code in web APIs. It does not make your code truly asynchronous β€” it only moves the blocking to another pool thread. In web APIs, this can worsen performance because it consumes an extra thread.

  • Name asynchronous methods with the Async suffix. It is a .NET convention: ObterTodosAsync, SalvarAsync, EnviarEmailAsync. It makes it clear that the method returns a Task and should be awaited.


Common Mistakes (and How to Avoid Them)

❌ Using .Result or .Wait() (can cause deadlock)

1
2
3
4
5
// ❌ WRONG β€” can cause deadlock in contexts with SynchronizationContext
var dados = ObterDadosAsync().Result;

// βœ… CORRECT β€” use await
var dados = await ObterDadosAsync();

❌ Not propagating CancellationToken

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// ❌ WRONG β€” ignores the client's cancellation
public async Task<List<Produto>> ObterTodosAsync(CancellationToken ct)
{
    return await _dbContext.Produtos.ToListAsync(); // Token not propagated!
}

// βœ… CORRECT β€” propagates the token
public async Task<List<Produto>> ObterTodosAsync(CancellationToken ct)
{
    return await _dbContext.Produtos.ToListAsync(ct);
}

❌ Using Thread.Sleep in asynchronous code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// ❌ WRONG β€” blocks the ThreadPool thread
public async Task ProcessarAsync()
{
    Thread.Sleep(5000); // Blocks!
    await FazerAlgoAsync();
}

// βœ… CORRECT β€” releases the thread
public async Task ProcessarAsync()
{
    await Task.Delay(5000); // Does not block
    await FazerAlgoAsync();
}

Conclusion

Asynchronous programming in C# with async/await is one of the most powerful tools in .NET for building scalable, responsive applications. As I showed throughout this article, asynchronous is not parallelism β€” they are complementary concepts that solve different problems. Asynchronous code shines in I/O operations, releasing threads to serve more requests with fewer resources.

Understanding how threads work and what it means to be thread-safe is essential to avoid subtle, hard-to-reproduce bugs, such as race conditions. And CancellationToken is indispensable for professional applications: it lets your API release resources immediately when a request is canceled, improving scalability and user experience.

In practice, remember: use async/await for every I/O operation, propagate the CancellationToken through the whole call chain (from the controller to the database), avoid .Result and .Wait(), and never confuse Thread.Sleep with Task.Delay. If you follow these rules, your C# code will be more efficient, more resilient and more professional.

If you liked this article and want to keep improving your skills, explore the other content on the blog β€” from security with BFF Backend For Frontend to task automation with Makefile.

πŸ’‘ Final tip: If the language or framework you use day to day does not offer native support for asynchronous programming β€” or implements it in a complex, verbose and error-prone way β€” it is worth seriously considering adding to your portfolio a mature language that treats asynchrony as a first-class citizen. C# is an excellent option: as I showed throughout this article, you just use async, await and CancellationToken to write clean, safe and performant asynchronous code β€” no nested callbacks, no manual thread management and no external libraries. The .NET ecosystem offers native asynchronous support in practically everything: Entity Framework, HttpClient, file I/O, streams, gRPC channels and even all of ASP.NET Core. Investing in a language that makes asynchronous code easy to write is not just a matter of productivity β€” it is a competitive advantage in the market.


Read Also


References