The Async Code Readability Wall
Writing responsive applications requires asynchronous operations (like fetching web services or querying databases without blocking the main UI thread). Traditionally, this meant using:
- ◆Asynchronous Programming Model (APM): Writing matching Begin/End execution pairs.
- ◆Event-based Asynchronous Pattern (EAP): Wire up event handlers to capture completions.
These models split application logic across multiple callbacks, making error handling and loops incredibly difficult to structure.
Microsoft's preview of async and await in C# 5.0 is a revolutionary shift in language design.
The Async/Await Syntax Pattern
Async/await allows developers to write asynchronous code that reads like standard synchronous code:
// Asynchronous database fetch in C# 5.0
public async Task<User> FetchUserAsync(int id) {
// Execution suspends here and returns control to caller
var user = await _context.Users.FindAsync(id);
return user;
}The C# compiler completely rewrites this method behind the scenes, generating a complex state machine that registers callbacks and handles execution resumes automatically when the Task completes.
Synchronization Context Handling
The runtime engine automatically marshals control back to the originating thread context (such as the WPF or WinForms UI thread) on resume, preventing cross-thread exceptions without requiring manual dispatch wrappers, establishing a new concurrency standard.