Loading…
Loading…
50 карточек
How does async/await work in C#?
нажми, чтобы перевернуть
The compiler transforms an async method into a state machine. On await, if the Task isn't complete — the method returns control to the caller. When the Task completes — the continuation is scheduled in the SynchronizationContext (UI thread) or ThreadPool. Return types: Task, Task<T>, ValueTask<T>, void (only for event handlers).
public async Task<User> GetUserAsync(int id)
{
// Поток не блокируется во время ожидания
var json = await httpClient.GetStringAsync($"/users/{id}");
return JsonSerializer.Deserialize<User>(json);
}
// АНТИПАТТЕРН: .Result блокирует поток
// var user = GetUserAsync(1).Result; // deadlock risk!Когда да
Any I/O operations: HTTP requests, file reading, DB queries
Когда нет
CPU-bound computations — use Task.Run to offload to ThreadPool
Совет на собеседовании
Mention ConfigureAwait(false) in library code — SynchronizationContext isn't needed.
Свайп вправо — знаю, влево — не знаю
