IC Improve Code Recipes

Recipe 1.7 · C#

Async Data Access All the Way Down

Problem

Data access is I/O, and a thread that waits for SQL Server is a thread that cannot serve another request. Most enterprise code I have inherited ignores this: async/await appears in only about 0.3% of the hand-written C# files in my archive (1,265 files, 11 of 35 engagements). Async fixes that, but only when it is async from the controller to the reader. Half-async code, with .Result or .Wait() somewhere in the middle, deadlocks in classic ASP.NET and starves the thread pool in ASP.NET Core. Another common problem is loading an entire result set into a list just to write it to a file.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: sync over async, and everything in memory.
public List<AuditEntry> GetAudit(DateTime from)
{
    return GetAuditAsync(from).Result;  // deadlock risk
}

public ActionResult Export(DateTime from)
{
    var all = GetAudit(from);           // 2 million rows
    var csv = string.Join("\n", all.Select(a => a.ToCsv()));
    return File(Encoding.UTF8.GetBytes(csv), "text/csv");
}

The improved recipe

C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;

namespace ImproveCode.Data;

public sealed record AuditEntry(
    long AuditId, DateTime ChangedUtc, string Description);

public sealed class AuditExport(IDbConnectionFactory db)
{
    private const string Sql = """
        SELECT AuditId, ChangedUtc, Description
        FROM dbo.AuditLog
        WHERE ChangedUtc >= @FromUtc
        ORDER BY AuditId;
        """;

    public async IAsyncEnumerable<AuditEntry> StreamAsync(
        DateTime fromUtc,
        [EnumeratorCancellation] CancellationToken ct = default)
    {
        await using var connection = await db.OpenAsync(ct);
        await using var command = new SqlCommand(Sql, connection)
        {
            CommandTimeout = 120
        };
        command.Parameters.AddDateTime2("@FromUtc", fromUtc);

        await using var reader = await command.ExecuteReaderAsync(
            CommandBehavior.SequentialAccess, ct);
        while (await reader.ReadAsync(ct))
        {
            yield return new AuditEntry(
                reader.GetInt64(0),
                reader.GetDateTime(1),
                reader.GetString(2));
        }
    }

    public async Task WriteCsvAsync(
        DateTime fromUtc, TextWriter output,
        CancellationToken ct = default)
    {
        await output.WriteLineAsync("AuditId,ChangedUtc,Description");
        await foreach (AuditEntry e in StreamAsync(fromUtc, ct))
        {
            string description =
                "\"" + e.Description.Replace("\"", "\"\"") + "\"";
            await output.WriteLineAsync(string.Join(',',
                e.AuditId.ToString(CultureInfo.InvariantCulture),
                e.ChangedUtc.ToString("O", CultureInfo.InvariantCulture),
                description));
        }
        await output.FlushAsync(ct);
    }
}

How it works

StreamAsync is an async iterator. It opens the connection, runs the query, and yields one AuditEntry per row as the reader advances. Only one row is in memory at a time. The connection stays open while the caller enumerates and closes when the await foreach loop finishes, breaks or throws, because the iterator's await using declarations run on disposal.

[EnumeratorCancellation] connects the token passed to StreamAsync with any token passed through WithCancellation, so a cancelled HTTP request stops the query. CommandBehavior.SequentialAccess tells the reader not to buffer the whole row, which matters for wide rows and large text columns; it requires that you read columns in order, as the mapping does.

WriteCsvAsync shows the consuming side. In ASP.NET Core you can pass a StreamWriter over Response.Body and the file streams to the browser as it is read from the database. Chapter 11 has a complete CSV writer; the quoting here is the minimum needed to be correct.

Variations and pitfalls

  • Never block on async. No .Result, .Wait() or .GetAwaiter().GetResult() in request code. If a synchronous caller cannot be changed, keep a synchronous method that calls the synchronous ADO.NET API rather than wrapping the async one.
  • Pass the token everywhere. Every OpenAsync, ExecuteReaderAsync and ReadAsync takes a CancellationToken. Cancellation sends an attention signal to SQL Server, which stops the query on the server, not just on the client.
  • ConfigureAwait(false). In ASP.NET Core and console apps there is no synchronization context, so it changes nothing. In a library that may be called from .NET Framework ASP.NET or WinForms, add .ConfigureAwait(false) to each await.
  • Large MAX columns. Reading big VARBINARY(MAX) or NVARCHAR(MAX) values with ReadAsync and GetString has historically been slow in SqlClient. Use SequentialAccess with GetStream or GetTextReader and copy the value in chunks.
  • Do not stream across a slow consumer for hours. The connection, and any shared locks under the default isolation level, stay open while the caller enumerates. For long exports, page through the data by key (Chapter 2) instead.