async/await lets you write non-blocking code that looks synchronous—ideal for I/O-bound work. The CLR rewrites async methods into state machines; this lesson uses Task.Delay to simulate I/O without blocking threads—unlike callback pyramids in older JavaScript.
Basic pattern
async Task<int> FetchCountAsync() {
await Task.Delay(100); // simulated I/O
return 42;
}
int n = await FetchCountAsync();
await yields the thread while waiting—important for scalable servers covered later in ASP.NET.
Rules of thumb
- Suffix async methods with
Async - Avoid
.Resultand.Wait()on async code—they can deadlock UI/ASP.NET contexts - Use
async Taskfor void-like async work; avoidasync voidexcept event handlers
Important interview questions and answers
- Q: async vs multithreading?
A: Async frees threads during I/O waits; CPU-bound parallelism usesTask.RunorParallelseparately. - Q: What does await return?
A: It unwraps the task result (or propagates exceptions) once the operation completes.
Self-check
- Why avoid blocking .Result on ASP.NET requests?
- What return type for async methods with no result?
Pitfall: Never block on async code with .Result or .Wait() on UI or ASP.NET threads—use await all the way.
Interview prep
- What does async return?
An awaitable
TaskorTask<T>—the method runs synchronously until the firstawait, then returns control.- Why avoid .Result?
Blocking on async code can deadlock on synchronization contexts (UI, ASP.NET)—use
awaitall the way.