14. Async, Threading & Concurrency
Part 1: Core Concepts
The Big Picture
┌─────────────────────────────────────────────────────┐
│ CONCURRENCY │
│ (Doing multiple things in overlapping time periods)│
│ │
│ ┌──────────────────────┐ ┌──────────────────────┐ │
│ │ PARALLELISM │ │ ASYNCHRONOUS │ │
│ │ (True simultaneous │ │ (Non-blocking, │ │
│ │ execution on │ │ waiting without │ │
│ │ multiple cores) │ │ blocking threads) │ │
│ │ │ │ │ │
│ │ • Parallel class │ │ • async/await │ │
│ │ • PLINQ │ │ • Task (I/O bound) │ │
│ │ • Task (CPU bound) │ │ • TAP pattern │ │
│ └──────────────────────┘ └──────────────────────┘ │
│ │
│ BOTH Built on: Thread & Task │
└─────────────────────────────────────────────────────┘Key Relationships
Part 2: Synchronous vs Asynchronous
Synchronous Execution
Asynchronous Execution
Blocking vs Non-Blocking
Part 3: CPU-Bound vs I/O-Bound
CPU-Bound Work
I/O-Bound Work
Part 4: Thread (Legacy Approach)
Thread Basics
Thread Properties
Thread Methods
Problems with Threads
Part 5: Task & Task<T> (Modern Approach)
Task vs Task<T>
Creating Tasks
Task Properties
Waiting for Tasks
Task Continuation
Multiple Tasks
ConfigureAwait
Part 6: async / await (The Game Changer)
Syntax Rules
Key Rules
Return Types
Async vs Sync Example
Async All The Way
Part 7: TAP (Task-based Asynchronous Pattern)
TAP Rules
TAP Example
TAP vs Other Patterns
Pattern
Era
Example
Part 8: Parallel Programming (CPU-Bound)
Parallel Class
Parallel.For
Parallel.ForEach
Parallel.Invoke
ParallelOptions
Part 9: PLINQ (Parallel LINQ)
Basic Usage
PLINQ Options
Part 10: CancellationToken & CancellationTokenSource
CancellationTokenSource
Using CancellationToken
Cancellation Callback
Part 11: Thread Safety & Synchronization
The Problem: Race Conditions
Solution 1: lock (Monitor)
Solution 2: Interlocked
Solution 3: Concurrent Collections
Solution 4: SemaphoreSlim
Solution 5: ReaderWriterLockSlim
Part 12: ThreadPool
Part 13: Async Coordination Primitives
TaskCompletionSource<T>
ManualResetEventSlim / AutoResetEvent
Part 14: Common Patterns
Pattern 1: Progress Reporting
Pattern 2: Timeout Pattern
Pattern 3: Retry Logic
Pattern 4: Lazy Initialization (Thread-Safe)
Pattern 5: Async Lazy
Part 15: Common Pitfalls
Pitfall 1: Deadlock with .Result or .Wait()
Pitfall 2: Async Void
Pitfall 3: Capturing Loop Variables
Pitfall 4: Starting Too Many Tasks
Part 16: Async Streams (C# 8.0+)
Part 17: ValueTask<T> (Performance)
Decision Tree: What to Use When?
Quick Reference Summary
Most Common Scenarios
Last updated