Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 182 ยท Async and Concurrency

Threads

Learn C# threads from scratch - starting a Thread, Join, foreground and background threads, race conditions and lock, the ThreadPool, ThreadLocal and why tasks are usually better.

A computer does many things at once: it plays music while you type, downloads a file while you scroll. A program gets that ability through threads. A thread is an independent path of execution inside your process: it has its own call stack and its own "current line", but it shares the process's memory (the heap) with every other thread. Your program has always had at least one, the main thread that runs your Main method or top-level statements.

Threads are the lowest-level concurrency tool in .NET. Modern code mostly uses tasks and async/await, which are built on top of threads. But you cannot understand tasks, locks or deadlocks without understanding threads first, and some jobs (a dedicated long-running loop, a thread with a big stack) still call for one. This lesson covers creating and joining threads, what goes wrong when threads share data, the thread pool, and why you should usually reach for something higher-level.

Our editor runs your program on a server with a single CPU and compares the output you see. Threads still work there, but the order in which two running threads print is up to the operating system and can differ from run to run. Every example on this page is written so its output is deterministic, using Join and locks, and the text says when order is not guaranteed.

Starting and joining a thread

Create a Thread with a method to run, then call Start. The new thread runs concurrently with the code that started it. To wait for it to finish, call Join from the other thread.

C# Thread, Start and Join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Without worker.Join(), "main: the worker has finished" could appear first, or the program could even reach its end while the worker was still running. Join blocks the calling thread until the other thread ends, so the three lines are guaranteed to print in this order.

The thread's body is the lambda you passed in. A thread ends when that method returns. If it throws an exception that nobody catches, the whole process crashes: exceptions do not travel from a thread to the thread that started it. Put a try/catch inside the thread body if it can fail.

Passing data in and getting results out

A Thread constructor takes a ThreadStart (no parameters) or a ParameterizedThreadStart (one object? parameter). The easiest way to pass values is simply to capture them in the lambda. There is no return value, so a result has to be written into a variable the main thread can read after Join.

C# Passing arguments and collecting results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two details are worth remembering. The copy int part = t; matters because a for loop variable is shared by every lambda created inside it; without the copy, both threads could see t == 2 by the time they run. And each thread writes to a different array slot, so no two threads touch the same memory. That is the safest kind of sharing.

Foreground and background threads

Every Thread has an IsBackground property. By default it is false: a foreground thread keeps the process alive until it finishes, even after Main returns. A background thread is killed as soon as all foreground threads are done. Use background threads for helpers that should never block shutdown (a cache cleaner, a heartbeat), and foreground threads for work that must complete.

C# Foreground versus background

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The program ends right after the foreground thread prints, long before the two seconds are up, and the background thread's line never appears. The first line from main is printed immediately; the foreground thread prints about 100 ms later.

Thread states and the life of a thread

A thread moves through a small set of states, which you can read from Thread.ThreadState (a flags enum) or the simpler IsAlive:

stateDiagram-v2
    [*] --> Unstarted: new Thread(...)
    Unstarted --> Running: Start()
    Running --> WaitSleepJoin: Sleep, Join, lock wait, Monitor.Wait
    WaitSleepJoin --> Running: wakes up or gets the lock
    Running --> Stopped: method returns or throws
    Stopped --> [*]

A stopped thread can never be started again.

  • Unstarted: created but Start() has not been called.
  • Running: executing code, or ready to run.
  • WaitSleepJoin: blocked because it called Thread.Sleep, Join, Monitor.Wait, waits on a lock held by another thread, or waits on a wait handle. This one state covers all kinds of blocking.
  • Stopped: the thread's method has finished.

The Background flag is combined with these, as you see in the output below. The old Thread.Abort does not exist in modern .NET (it throws PlatformNotSupportedException), so the way to stop a thread is cooperative: set a flag or use a CancellationToken that the thread checks regularly.

C# Watching thread states

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Note that the main thread is a foreground thread, while thread-pool threads are always background threads: if your Main returns while a pool job is still running, the process exits and the job is cut off. That is a common surprise with fire-and-forget work.

Choosing a synchronization primitive

Besides lock, .NET has several tools for coordinating threads. The synchronization lesson covers them in depth; this table is the overview:

Tool Use it when
lock / Monitor Only one thread at a time may run a section of code inside one process
Mutex Same, but across processes (a named mutex stops a second copy of your app from starting)
Semaphore / SemaphoreSlim At most N threads may enter, such as limiting 3 parallel downloads
ManualResetEventSlim, AutoResetEvent One thread signals another that "something happened"
Interlocked A single atomic number update, such as a counter

Shared data and race conditions

Now the dangerous part. When two threads read and write the same variable, the result can depend on exact timing. That is a race condition. The classic example is a counter. The statement count++ looks like one step, but the machine does three: read the value, add one, write it back. If two threads both read 7 before either writes, both write 8, and one increment is lost.

C# A lock makes the counter correct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The lock statement lets only one thread at a time enter its block. The other three wait at the door, so each _value++ happens completely before the next begins. System.Threading.Lock is the dedicated lock type introduced in .NET 9; a plain object also works. The synchronization lesson explains locks, Interlocked and their costs in depth.

What if you remove the lock? The result is unpredictable, and that is the point: the total is usually less than 40,000, and it differs between runs and machines. On a single CPU the damage is often hidden (a thread is rarely interrupted at exactly the wrong instruction), which makes this bug especially nasty: it passes on your laptop and fails in production. We deliberately do not run the broken version here because its output would not be stable. Instead, here is the quick way to avoid the whole problem for a simple counter:

C# Interlocked for single-variable updates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Interlocked.Increment is an atomic CPU operation: no lock needed and the result is always exactly 40000.

A race condition is not an exception. Nothing crashes and no message appears; the program just gives wrong answers sometimes. Treat every variable that more than one thread can write as dangerous until it is protected by a lock, an Interlocked call, a concurrent collection, or by making it immutable.

The thread pool

Creating a thread is expensive. Each one reserves about 1 MB of stack space by default and costs the operating system time to set up. A program that starts a thread for every small job wastes both. The thread pool solves this by keeping a set of ready-made worker threads. You hand it a piece of work, and an idle thread picks it up.

C# Queueing work on the thread pool

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Pool threads are always background threads. The CountdownEvent is a small synchronization tool: the main thread calls Wait, and each work item calls Signal when it finishes; when three signals have arrived, Wait returns. The order in which the three "is pool thread" lines appear is not guaranteed, but all three always print True. The pool grows and shrinks on its own, so avoid blocking pool threads for a long time. Tasks run on this pool, which is the main reason you rarely call QueueUserWorkItem yourself.

Thread-local data

Sometimes each thread needs its own copy of a value, for example a random number generator or a scratch buffer, so no locking is required. ThreadLocal<T> creates one lazily per thread.

C# ThreadLocal gives each thread its own value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each thread adds to its own value (5 and 10), and the main thread, which never touched it, still sees 0. A simpler cousin is the [ThreadStatic] attribute on a static field, but be careful: its initializer runs only for the first thread. Prefer ThreadLocal<T>.

Why we prefer tasks

Raw threads have real drawbacks: they are heavy, they have no return value, an unhandled exception kills the process, you must Join them manually, and composing "do these three things, then that" is clumsy. A Task represents an operation that will complete in the future. It runs on the thread pool, carries a result or an exception, and works with await so the code stays readable. Remember this rule of thumb:

  • I/O waiting (network, files, timers): use async/await, no thread is blocked.
  • CPU work in the background: Task.Run (see Tasks) or Parallel and PLINQ.
  • A long-lived dedicated loop, or a special stack size or priority: a real Thread, often with IsBackground = true.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does thread.Join() do?

    Join waits for the target thread to end. It does not start or stop anything.
  2. 2. Four threads each run count++ 10,000 times on a shared int with no protection. What is guaranteed?

    count++ is read, add, write. Interleaved threads can lose updates, so the result can be lower than 40,000 (and varies between runs). Nothing throws.
  3. 3. What happens to a background thread when all foreground threads have finished?

    Background threads do not keep the process alive; they are stopped when the process exits.
  4. 4. What happens if a thread body throws an exception that nothing catches?

    Exceptions do not cross threads. An unhandled one terminates the process, so catch inside the thread body.
  5. 5. Which tool gives every thread its own private copy of a value?

    ThreadLocal<T> keeps a separate value per thread, so no locking is needed for it.

Summary

  • A thread is an independent path of execution that shares the process's memory; the program starts with one main thread.
  • Start begins a thread and Join waits for it. Uncaught exceptions in a thread crash the process.
  • Foreground threads keep the process alive; background threads do not.
  • Shared mutable data needs protection: lock, Interlocked, concurrent collections, or immutability. Race conditions give wrong answers without any error.
  • The thread pool reuses threads; ThreadLocal<T> gives each thread its own value.
  • Prefer tasks and async/await for almost everything; use a dedicated Thread only for special cases.

Next: Tasks and the Task Parallel Library