skip to content

Your team is moving a synchronous C# weather library, and the console tool and desktop app that call it, to async; where do you start, how far do you go, and where do you stop?

level: principalimportance: should knowfreq 35%

answer

  1. await forces async upward
  2. start at the I/O calls
  3. the entry point is the top
  4. no blocking bridges in the middle
  5. pure computation stays synchronous

basics

~20 s

Start at the I/O calls, switch them to truly asynchronous APIs, and let Task-returning signatures spread up to the entry points: async Main in the console tool, async event handlers in the desktop app, with no .Result bridges or Task.Run wrappers between.

solid answer

~50 s

Async spreads upward because `await` is only legal inside an `async` method (CS4032, CS4033), so the conversion runs **bottom-up**: replace each blocking network call with its asynchronous counterpart, make its method return `Task` or `Task<T>`, and repeat for every caller until you reach an entry point. The console tool's top becomes `static async Task<int> Main` or top-level statements with `await`; the desktop app's top is its event handlers, the one place `async void` belongs. In a public library, add `GetForecastAsync` **beside** `GetForecast` rather than replacing it, and implement neither by wrapping the other: no `.Result` inside the sync version, no `Task.Run` inside the async one. Stop where no I/O happens; pure computation stays synchronous. The judgment calls are how long to keep both APIs, how to version the changed interfaces, and which unavoidable synchronous boundaries get an isolated, documented bridge.

go deeper

for a junior

Recall why await forces callers to become async too, and that the console entry point and UI event handlers sit at the top of the chain.

for a middle

Explain the bottom-up order: start at the I/O calls, then walk up the callers, and why blocking with .Result in the middle defeats the change.

for a senior

Identify the places that cannot be async, such as constructors, property getters and synchronous framework callbacks, and handle each without hidden blocking.

for a principal

Own the plan: sequencing, side-by-side APIs versus a breaking replacement, interface versioning, a removal trigger for the synchronous surface, and guardrails for new code.

## Why async spreads In C#, `await` may appear only inside a method, lambda or local function marked `async`. A synchronous method that tries to await is rejected, and the compiler's message names the fix it expects: ```plaintext error CS4032: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<int>'. ``` Making that method `async` changes its return type to a task, so **its** callers must now await it, and so on up the call chain. This is why the guidance is usually summarised as **async all the way**: once the bottom of a call chain is asynchronous, every method between it and the entry point either becomes asynchronous too or blocks on a task, and blocking throws away the benefit and, on a UI thread, invites deadlock. The decision a lead owns is not whether this happens but **how to sequence it, where it stops, and what the public surface looks like while it is under way**. ## Start at the bottom A conversion that works in practice runs in this order: 1. **Find the I/O.** List the calls that wait on something outside the process: the HTTP calls to the three upstream weather services, file reads, database queries. Those are the only places asynchrony pays for itself. 2. **Switch each to a truly asynchronous API**, such as `HttpClient.GetStringAsync` instead of a blocking client, and make the enclosing method return `Task<T>`. 3. **Walk up the callers**, making each one `async` and awaiting the call. Add a `CancellationToken` parameter in the same pass, since every signature is changing anyway; how tokens behave is covered in the lesson on cancellation. 4. **Reach the entry points** and finish there (next section). 5. **Convert the tests** to `async Task` test methods, never `async void`, so the runner awaits them. Working top-down instead, making the UI handler `async` first and then blocking further down, leaves a blocking call in the middle of the chain at every intermediate step. ## The top of the chain - **Console tool.** Since C# 7.1 `Main` may be `static async Task Main()` or return `Task<int>` for an exit code. With top-level statements, using `await` in them makes the compiler generate an asynchronous entry point. - **Desktop app.** The tops are the event handlers. They stay `async void`, because their delegate types return `void`, and each catches and reports its own exceptions. ## Where to stop - **Pure computation** such as unit conversion or forecast averaging stays synchronous. Wrapping it in `Task` adds overhead and no benefit; if it is heavy, the UI caller offloads it with `Task.Run` at the call site. - **Members that cannot be async.** Constructors and property getters cannot be marked `async`. Use an asynchronous factory method or an explicit `InitializeAsync`, and expose asynchronous data through methods rather than properties. - **Synchronous contracts you do not own**, such as a framework callback with a synchronous signature. There a bridge may be unavoidable. Keep it in one place, document it, and make sure it never runs on a UI thread; why blocking on a task can deadlock is covered with synchronization contexts. ## Sync and async side by side | Strategy for the library's public API | Benefit | Cost | |---|---|---| | Add `...Async` methods beside the synchronous ones | callers migrate at their own pace, no breaking change | two code paths to maintain and test | | Replace synchronous methods with `...Async` | one code path | breaking change for every caller and implementer | | Implement sync by blocking on async (`.Result`) | one real implementation | deadlock risk on UI threads, a blocked thread per call | | Implement async with `Task.Run` around sync | quick to write | no scalability gain; callers are misled by the name | Microsoft's Task-based Asynchronous Pattern guidance recommends the first row for existing libraries: add the `MethodNameAsync` overload alongside the synchronous method and do not remove or rename the synchronous one. Its separate articles on synchronous and asynchronous wrappers argue against the last two rows. ## What a lead decides - **Sequencing:** which call chains go first, usually the ones with the most I/O wait or the worst UI freezes. - **Interface versioning:** changing `IForecastSource.Get` to return `Task<Forecast>` breaks every implementer; decide whether to add a new interface, a new member, or a major version. - **Deprecation horizon:** how long the synchronous API is kept, and the trigger for removing it. - **Guardrails:** analyzer rules or review checks that reject `.Result`, `.Wait()` and `async void` outside event handlers in new code. - **Success measure:** responsiveness and concurrent capacity, not raw speed; a single request does not get faster by becoming asynchronous.

  • A constructor needs data from the forecast service; how do you handle it once everything is async?
    A C# constructor cannot be marked `async`, and blocking on a task inside it reintroduces sync-over-async. Use a private constructor plus a `static async Task<WeatherDashboard> CreateAsync(...)` factory that awaits the data first, or an explicit `InitializeAsync` method that callers await before use.
  • Why not convert top-down, starting with the UI handlers?
    An `async` handler that calls still-synchronous code gains nothing, and the tempting interim fix, blocking on newly asynchronous lower layers with `.Result`, is exactly the pattern that deadlocks on a UI thread. Converting from the I/O upward means every intermediate state is either fully synchronous or genuinely asynchronous below the converted point.

  • Mark the top-level handler async and the rest of the codebase can stay synchronous
  • Calling .Result at each layer is a safe way to convert one layer at a time
  • Every method should return Task, including pure computations
  • Wrapping the old synchronous methods in Task.Run completes the migration
  • Going async makes each individual request faster