ASYNCHRONOUS PROGRAMMING
IN .NET
1. Introduction
• Asynchronous Programming in .NET
• Basic concepts to practical async/await
2. Synchronous Program Execution
• Code executes line by line
• Thread MUST WAIT
• Like queuing
• When to use:
- Simple code
- Fast CPU
- Easy to debug
• Problem: Thread blocked waiting for I/O
→ Waste of resources
3. Asynchronous Program Execution
• Code does NOT WAIT
• Thread RETURNS IMMEDIATELY
• Calls callback when done
• Benefits:
- Increase performance
- UI does not freeze
- Better resource utilization
• Patterns:
1. APM - NO LONGER SUPPORTED
2. EAP - Uses events
3. TAP - MOST MODERN
• Does async create new thread?
- I/O-bound: NO
- CPU-bound: MAY
• Async vs Parallel:
- Parallel: Divides work, multiple CPUs
- Async: Does not block thread
4. Demo 01: EAP Pattern
• EAP download web page
• Uses events for results
• Old pattern, use TAP
5. When to Use Asynchronous Programming
• I/O Operations:
- Read/write files
- Call APIs
- Database
- Email
• Reason:
- CPU does nothing waiting for I/O
- Thread does other work
• NOT for everything!
• Async does NOT make code faster directly
- Increases throughput
- Increases responsiveness
6. Introducing async and await
• async: Marks async method
• await: WAITS task, does NOT BLOCK thread
• Execution flow:
1. Call async → returns Task immediately
2. Thread does other work
3. await → thread released
4. Task done → continues
• async method returns Task/Task<T>
• await only in async method
• await does NOT BLOCK thread
• Compiler auto wraps Task
7. Demo 02: TAP Pattern
• TAP with async/await
• MOST MODERN and RECOMMENDED
• Advantages:
- Code easier to read
- Easier error handling
- Easier to combine
- Supports cancellation
8. Demo 03: WPF Application with HttpClient
• Download multiple websites simultaneously
• Download = I/O operation
• Synchronous → UI FREEZES
• Async → UI RESPONSIVE
• [Link] waits ALL tasks
• Download in parallel
9. Summary
• Synchronous: Sequential, waits each step
• Asynchronous: Does not block thread
• Use when: I/O operations, UI apps
• async/await: TAP pattern
• Benefits: Throughput, Responsiveness
• Async = MORE EFFICIENT!