Threads: The Extra Hands

Threads: The Extra Hands in C#: Picture a small restaurant with one cook. Orders arrive, the cook works through them one at a time, and everything is perfectly…

The Analogy: A Second Cook in the Kitchen

Picture a small restaurant with one cook. Orders arrive, the cook works through them one at a time, and everything is perfectly predictable: whatever is on the stove is the only thing being made, and the cook always knows the state of every pan. This is a single-threaded program. It is easy to reason about precisely because only one thing ever happens at once.

Then business picks up, and the owner hires a second cook. Suddenly two dishes progress at the same time and the kitchen finishes the evening's orders in half the time — but the shared things become dangerous. Two cooks reaching for the same knife, two cooks stirring the same pot, two cooks each reading "3 onions left" and each taking three. Nothing in the kitchen changed except the number of hands, and yet a whole category of problem appeared that simply could not exist before.

A thread is that extra cook. It is an independent path of execution through your code, with its own call stack and its own place in the program, sharing all the same memory as every other thread in the process. The sharing is the point — passing data between threads costs nothing because there is nothing to pass — and the sharing is also the entire difficulty, because two threads touching the same field at the same time have no more coordination than two cooks reaching for the same knife.

The important thing to internalise early is that extra hands do not create extra stoves. If your work is waiting on a database, more threads mostly means more threads waiting. If your work is genuine computation, more threads means real speed — up to the number of cores your machine actually has. This lesson is about the raw Thread type: what it costs, how you start and wait for one, and why modern C# almost always reaches for a higher-level tool instead.


Syntax or Core Structure

using System;
using System.Threading;

class Program
{
    static void Count(object? label)
    {
        for (int i = 1; i <= 3; i++)
            Console.WriteLine(label + " step " + i);
    }

    static void Main()
    {
        Thread worker = new Thread(Count) { Name = "worker" };
        worker.Start("worker");
        worker.Join();                       // block here until it finishes
        Console.WriteLine("worker finished, IsAlive = " + worker.IsAlive);

        Thread background = new Thread(() =>
            Console.WriteLine("background ran on a pooled-style thread"));
        background.IsBackground = true;       // will not keep the process alive
        background.Start();
        background.Join();

        Console.WriteLine("main is still thread " + Thread.CurrentThread.Name);
    }
}

Output:

worker step 1
worker step 2
worker step 3
worker finished, IsAlive = False
background ran on a pooled-style thread
main is still thread

That output is deterministic only because of the two Join calls. Remove them and the lines can interleave in any order, or the process can exit before the background thread prints at all — which is exactly the guarantee IsBackground gives up. Foreground threads keep the process alive until they finish; background threads are abandoned the moment Main returns.

Note the last line: Thread.CurrentThread.Name on the main thread is empty, because nobody named it. A thread's Name is write-once and purely for your benefit — it shows up in the debugger's thread window and in crash dumps, which is reason enough to always set it on threads you create by hand.

The two constructor overloads are worth separating. ThreadStart takes no arguments; ParameterizedThreadStart takes a single object?, which is why Count has that signature and why Start("worker") compiles. In practice the lambda form wins, because a closure can capture as many strongly-typed variables as you like without any casting.


Technical Depth: What a Thread Actually Costs

A thread is not a cheap object. Creating one asks the operating system for a scheduling unit and reserves stack space for it, and the runtime has to register it for garbage-collection bookkeeping.

ResourceTypical cost per threadConsequence
Reserved stack1 MB on Windows (committed lazily)1,000 threads reserve about a gigabyte of address space
Creation timeTens of microsecondsCreating one per request is measurable overhead
Context switchA few microsecondsMore runnable threads than cores means the CPU spends time switching, not working
GC bookkeepingEvery stack is a rootMore threads means longer stack scans during collection

This is why the runtime maintains a thread pool: a set of already-created worker threads that hand themselves out for short work items and return to the pool afterwards. ThreadPool.QueueUserWorkItem, every Task, every async continuation and every ASP.NET Core request runs on it. You almost never want a dedicated Thread — the exceptions are long-running or blocking-forever loops, threads that need a non-default stack size, and threads that must set apartment state for legacy COM interop.

Sleeping is not waiting

Thread.Sleep(1000) parks the thread for a second: it occupies a full thread and a full megabyte of stack in order to accomplish nothing. await Task.Delay(1000) releases the thread back to the pool and resumes on one afterwards. In a server, the first pattern is how you exhaust the pool under load; the second costs a timer registration.

The loop-variable capture trap

for (int i = 0; i < 3; i++)
    new Thread(() => Console.WriteLine(i)).Start();   // BUG: one shared i

for (int i = 0; i < 3; i++)
{
    int copy = i;                                    // fresh variable per iteration
    new Thread(() => Console.WriteLine(copy)).Start();
}

A for loop has exactly one i for the whole loop, and all three lambdas capture that same variable — so they typically print 3 three times, or some scrambled mix, depending on how fast the threads start. A foreach variable is per-iteration since C# 5 and is safe, but for is not. Copy into a local before capturing.

Per-thread state

[ThreadStatic] on a static field gives each thread its own copy, and ThreadLocal<T> does the same with a lazy factory and a Values view. Both are useful for things like per-thread random generators or scratch buffers, and both are traps in async code, where a single logical operation can resume on a different thread than it started on. AsyncLocal<T> is the flow-aware alternative.

Things that look useful and are not

Thread.Abort throws PlatformNotSupportedException on .NET Core and later — you cannot forcibly kill a thread, and the correct mechanism is a CancellationToken the worker checks. Thread.Priority is a hint the OS scheduler is free to ignore, and raising it usually just starves something else. Thread.Suspend and Resume are obsolete because suspending a thread that holds a lock deadlocks everything waiting on it.


Real World Example: Splitting a Long Calculation

A reporting job has to fold four million rows into one number. The work is pure computation, so extra cores genuinely help — and the trick that makes it safe is that no two threads ever touch the same memory location.

using System;
using System.Threading;

class Program
{
    const int Total = 4_000_000;

    static void Main()
    {
        const int workers = 4;
        int chunk = Total / workers;
        long[] partial = new long[workers];      // one slot per worker
        Thread[] threads = new Thread[workers];

        for (int w = 0; w < workers; w++)
        {
            int index = w;                        // copy before capturing
            int from = index * chunk + 1;
            int to = from + chunk - 1;

            threads[index] = new Thread(() =>
            {
                long sum = 0;
                for (int n = from; n <= to; n++) sum += n % 7;
                partial[index] = sum;             // no other thread writes here
            })
            { Name = "worker-" + index, IsBackground = true };

            threads[index].Start();
        }

        foreach (Thread t in threads) t.Join();    // all writes are visible after this

        long total = 0;
        for (int w = 0; w < workers; w++)
        {
            Console.WriteLine("partition " + w + " -> " + partial[w]);
            total += partial[w];
        }
        Console.WriteLine("total = " + total);
    }
}

Output:

partition 0 -> 2999998
partition 1 -> 2999999
partition 2 -> 3000000
partition 3 -> 3000001
total = 11999998

Every design decision here exists to remove a race. Each worker accumulates into a local sum — a variable on its own stack that no other thread can even name — and writes to the array exactly once, at an index no other worker uses. There is no shared counter, so there is no lock, and no lock means no contention and no deadlock. This "partition, compute locally, combine at the end" shape is the single most reliable pattern in parallel programming, and it is what Parallel.For and PLINQ generate for you underneath.

The Join loop does more than wait. It also establishes a memory barrier: without some synchronising operation, the main thread has no guarantee it would ever observe the workers' writes to partial, because a CPU is free to keep values in registers or a store buffer. Join is what makes "the writes happened before this line" a rule rather than a hope. Reading partial from a loop that merely spins until the threads look finished would be a genuine bug on some hardware.

Two honest caveats. First, the partitions are equal in size but not necessarily in duration, so the job finishes at the speed of the slowest partition — with uneven work you want more, smaller chunks. Second, Total / workers truncates: with Total = 4_000_001 the last row would silently be dropped. Real partitioning code gives the final chunk the remainder, and this is precisely the class of off-by-one that a library like Parallel.For has already got right.


Common Mistakes

  1. Capturing a for loop variable in a thread lambda. All iterations share one variable, so the threads see whatever value it holds when they happen to run. Copy it into a local first.
  2. Forgetting to Join, then reading the results. Without a join (or another synchronising wait) the main thread may read stale or partially written state, and the bug appears only under load or on a different machine.
  3. Creating a thread per work item. A thousand short jobs should be a thousand pool work items, not a thousand threads — the creation cost and context switching will outweigh the parallelism.
  4. Using Thread.Sleep to wait for another thread. It is a guess dressed as synchronisation. Use Join, a ManualResetEventSlim, or a Task.
  5. Expecting IsBackground = true work to complete. Background threads are killed when the process exits, so anything that must finish needs a foreground thread or an explicit wait.
  6. Letting an exception escape a thread's delegate. An unhandled exception on a background thread tears down the whole process, and Join will not rethrow it for you. Wrap the body in try/catch and record the failure yourself.
  7. Assuming more threads means more speed. Past the core count, CPU-bound work gets slower, not faster. Measure Environment.ProcessorCount and size the pool to the machine.
  8. Reaching for Thread.Abort or Thread.Priority. The first no longer works at all on modern .NET; the second is a hint the scheduler may ignore. Cooperative cancellation is the only reliable way to stop work.

Best Practices

  • Reach for Task and the thread pool first; create a raw Thread only for long-lived, blocking, or specially configured work.
  • Give every hand-created thread a Name — it is the difference between a readable and an unreadable crash dump.
  • Prefer the "partition, compute into thread-local state, combine after joining" shape over any design where two threads write the same location.
  • Copy loop variables into locals before capturing them in a thread or task lambda.
  • Always have a plan for exceptions inside the thread body: catch, record, and surface the failure to whoever waits.
  • Use a CancellationToken the worker polls, and mark long-running threads IsBackground = true so a hung worker cannot keep the process alive.
  • Size CPU-bound parallelism from Environment.ProcessorCount rather than a hard-coded number.
  • Never use Thread.Sleep as synchronisation, and never block a pool thread on I/O that has an async alternative.

Practice Exercises

  1. Run the partition example with workers set to 1, 2, 4 and 8, timing each with Stopwatch. Print the four timings alongside Environment.ProcessorCount and explain where the speed-up stops.
  2. Fix the truncation bug: change Total to 4_000_003 and adjust the partitioning so the last worker takes the remainder. Assert that the total matches a single-threaded loop over the same range.
  3. Write a worker thread that loops until a CancellationToken is cancelled, printing a heartbeat each half-second. Cancel it from Main after two seconds and join cleanly, printing how many heartbeats occurred.
  4. Demonstrate the capture bug for yourself. Start ten threads that print a captured for variable, run the program five times, and record the outputs. Then add the local copy and confirm the output becomes stable.