15 minlesson

What Are Threads?

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

ConceptDescription
ProcessAn independent program with its own memory space
ThreadA 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:

  1. Unstarted - Thread created but not yet started
  2. Running - Thread is executing
  3. WaitSleepJoin - Thread is blocked (waiting, sleeping, or joining)
  4. Stopped - Thread has completed execution
csharp
1Thread thread = new Thread(DoWork); // Unstarted
2thread.Start(); // Running
3thread.Join(); // Wait for completion
4// Thread is now Stopped

Why Multiple Threads?

1. Responsiveness

Keep the UI responsive while performing background work:

csharp
1// Without threads: UI freezes during download
2DownloadLargeFile(); // Blocks for 30 seconds
3
4// With threads: UI stays responsive
5Thread downloadThread = new Thread(DownloadLargeFile);
6downloadThread.Start();
7// UI continues to respond

2. Performance

Utilize multiple CPU cores for parallel computation:

csharp
1// Single-threaded: Uses 1 core
2ProcessAllImages(images); // Takes 8 seconds on 1 core
3
4// Multi-threaded: Uses 4 cores
5// Each thread processes 1/4 of images
6// Takes ~2 seconds on 4 cores

3. Scalability

Handle multiple client requests simultaneously:

csharp
1// Server handling multiple clients
2while (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:

ResourceCost per Thread
Stack memory~1 MB default
Kernel objectOS resources
Context switchCPU cycles
Creation timeMilliseconds

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