A typical async/await snippet interviewers expect you to write and explain: public sealed class WeatherService(HttpClient http, ILogger<WeatherService> logger) { public async Task<Forecast?> GetForecastAsync(string city, CancellationToken ct) { try { using var response = await http.GetAsync($"forecast/{Uri.EscapeDataString(city)}", ct); if (response.StatusCode == HttpStatusCode.NotFound) return null; response.EnsureSuccessStatusCode(); return await response.Content.ReadFromJsonAsync<Forecast>(ct); } catch (HttpRequestException ex) { logger.LogWarning(ex, "Forecast service failed for {City}", city); throw; } } } // Controller [HttpGet("{city}")] public async Task<IActionResult> Get(string city, CancellationToken ct) { var forecast = await _weather.GetForecastAsync(city, ct); return forecast is null ? NotFound() : Ok(forecast); } What to explain - async marks the method so the compiler builds a state machine; the method returns Task or Task<T>. - At each await on an incomplete operation, the thread is released; when the HTTP call finishes, execution continues after the await. - The CancellationToken stops the work if the client disconnects. - Exceptions thrown in the async method are captured in the Task and rethrown at await, so try/catch works normally. Running independent calls in parallel: var weatherTask = _weather.GetForecastAsync(city, ct); var newsTask = _news.GetHeadlinesAsync(city, ct); await Task.WhenAll(weatherTask, newsTask); return new Dashboard(await weatherTask, await newsTask); Common mistakes interviewers look for (and how to fix them) // 1. Blocking: can deadlock (UI or classic ASP.NET) or starve threads (ASP.NET Core) var data = GetDataAsync().Result; // wrong var data = await GetDataAsync(); // right // 2. async void: exceptions crash the process or are lost public async void Save() { ... } // wrong (except event handlers) public async Task SaveAsync() { ... } // right // 3. Forgetting to await: the work runs unobserved SendEmailAsync(user); // wrong — warning CS4014 await SendEmailAsync(user); // right // 4. Sequential awaits for independent work var a = await GetAAsync(); var b = await GetBAsync(); // slower await Task.WhenAll(...) // parallel Also mention ConfigureAwait(false) in library code, and ValueTask for hot paths that often complete synchronously.
Ravindra Wadile · · 0 likes