What Are Threads?
A thread is the smallest unit of execution that can be scheduled by the operating system. Understanding threads is fundamental to mastering async programming in C#.
Process vs Thread
| Concept | Description |
|---|---|
| Process | An independent program with its own memory space |
| Thread | A unit of execution within a process that shares memory |
A single process can have multiple threads running concurrently:
1┌─────────────────────────────────────┐2│ Process │3│ ┌─────────┐ ┌─────────┐ ┌─────────┐│4│ │ Thread 1│ │ Thread 2│ │ Thread 3││5│ └─────────┘ └─────────┘ └─────────┘│6│ Shared Memory Space │7└─────────────────────────────────────┘
Thread Lifecycle
A thread goes through several states during its lifetime:
- Unstarted - Thread created but not yet started
- Running - Thread is executing
- WaitSleepJoin - Thread is blocked (waiting, sleeping, or joining)
- Stopped - Thread has completed execution
csharp1Thread thread = new Thread(DoWork); // Unstarted2thread.Start(); // Running3thread.Join(); // Wait for completion4// Thread is now Stopped
Why Multiple Threads?
1. Responsiveness
Keep the UI responsive while performing background work:
csharp1// Without threads: UI freezes during download2DownloadLargeFile(); // Blocks for 30 seconds34// With threads: UI stays responsive5Thread downloadThread = new Thread(DownloadLargeFile);6downloadThread.Start();7// UI continues to respond
2. Performance
Utilize multiple CPU cores for parallel computation:
csharp1// Single-threaded: Uses 1 core2ProcessAllImages(images); // Takes 8 seconds on 1 core34// Multi-threaded: Uses 4 cores5// Each thread processes 1/4 of images6// Takes ~2 seconds on 4 cores
3. Scalability
Handle multiple client requests simultaneously:
csharp1// Server handling multiple clients2while (true)3{4 var client = server.AcceptClient();5 Thread handler = new Thread(() => HandleClient(client));6 handler.Start();7}
The Cost of Threads
Threads are not free - they come with overhead:
| Resource | Cost per Thread |
|---|---|
| Stack memory | ~1 MB default |
| Kernel object | OS resources |
| Context switch | CPU cycles |
| Creation time | Milliseconds |
Creating thousands of threads is inefficient. This is why the Thread Pool exists (covered in the next lesson).
Key Takeaways
- A thread is a unit of execution within a process
- Multiple threads share the same memory space
- Threads enable responsiveness, performance, and scalability
- Threads have overhead - don't create too many
- Modern C# uses higher-level abstractions (Tasks) built on threads