LLearnCode
Academy/csharp/Trust boundaries and asynchronous work

advanced · 29 minute study

Decode data and release resources at explicit boundaries

Build import/export utilities without treating a successfully deserialized file as automatically valid domain data.

Loading progressEvidence grows with practice
Useful preparation · 1 prerequisite

Use this as a map, not a lock. If these ideas are familiar, continue.

First, build a mental model

A file handle is a resource with a lifetime. JSON is external data with a shape and meaning that may differ from your current model. Release the resource and validate the data as two separate responsibilities.

  1. using disposes an IDisposable resource when its scope ends, including when an exception leaves the scope.
  2. Use await using for an IAsyncDisposable resource when asynchronous disposal is appropriate; it is not a replacement for every using.
  3. DeserializeAsync<T> can fail or produce null; matching C# types does not prove domain validity.
  4. Validate required fields and allowed ranges before turning a transport DTO into trusted application state. Avoid accepting arbitrary file paths from untrusted input.
Read the codecsharp · educational example
using System.Text.Json;

using var stream = File.OpenRead("player.json");
PlayerDto? dto = await JsonSerializer.DeserializeAsync<PlayerDto>(stream);
if (dto is null || string.IsNullOrWhiteSpace(dto.Name) || dto.Score < 0)
    throw new InvalidDataException("Invalid player file");
Console.WriteLine(dto.Name);

record PlayerDto(string Name, int Score);
// Example file: {"Name":"Ada","Score":12}
  1. Acquire

    OpenRead returns a stream owned by this scope.

  2. Decode and validate

    The code checks both an actual DTO and the name/score rules.

  3. Release

    The using declaration disposes the stream when the scope ends, even on rejection.

Production thinking

Take this beyond the example.

Version persisted schemas, bound import sizes and preserve a recoverable prior state. Test malformed JSON, missing fields, permission errors and interrupted writes using synthetic files.

Sources and further reading

Your evidence

unseen is a local learning signal, not a credential or proof of production competence.

Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.

Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.

Next lesson · A deterministic test controls the sources of uncertainty →