Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Thread.Start/Join and Monitor.Wait/PulseAll: threads and conditions

Start a real thread, use a monitor to wait for shared state to change, and wait separately for the thread to finish. A notification does not prove that the condition is true.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

using System.Threading;

// Thread — instance methods
void Start();
void Start(object? parameter);
void Join();
bool Join(int millisecondsTimeout);
bool Join(TimeSpan timeout);

// Monitor — static methods
static bool Wait(object obj);
static bool Wait(object obj, int millisecondsTimeout);
static bool Wait(object obj, TimeSpan timeout);
static bool Wait(object obj, int millisecondsTimeout, bool exitContext);
static bool Wait(object obj, TimeSpan timeout, bool exitContext);
static void PulseAll(object obj);

// Waiter: check the condition while holding the monitor.
lock (gate) { while (!ready) Monitor.Wait(gate); }

// Publisher: update the condition before notifying waiters.
lock (gate) { ready = true; Monitor.PulseAll(gate); }

Thread.Start and Thread.Join manage a thread's lifetime, while Monitor.Wait and Monitor.PulseAll coordinate access to shared state. In C# 12 and .NET 8, Thread instance method Start() schedules the thread without waiting for its delegate to finish. Start(object?) passes an argument to ParameterizedThreadStart; using that overload with ThreadStart throws InvalidOperationException. Calling Start() with ParameterizedThreadStart passes null. Starting the same thread twice throws ThreadStateException, even after it has terminated.

Join() blocks the caller until the target thread terminates. The int (milliseconds) and TimeSpan overloads return true if it terminated or false if the wait timed out. Join does not stop the thread and throws ThreadStateException for a thread that hasn't been started. Never call indefinite Join() on the current thread or while holding a lock the target needs: either can deadlock.

Use the same dedicated, unexposed gate object for every read and write of the shared state. With an object, lock (gate) uses Monitor.Enter and Monitor.Exit, releasing the lock even on exception; TryEnter tries to acquire it, not to wait for a condition. The static methods Monitor.Wait(gate) and Monitor.PulseAll(gate) require the caller to own that object's lock; otherwise they throw SynchronizationLockException. Wait temporarily releases only that lock and reacquires it before returning, restoring the recursion depth. Timed overloads (int milliseconds or TimeSpan) return a bool about timing, not about the condition. Reacquiring the lock can take longer than the timeout. The overloads that accept exitContext are available in .NET 8, but the runtime ignores that argument.

While holding the lock, update the state before calling PulseAll. It moves all current waiters on that monitor to the ready queue (Pulse moves only one), but does not release the lock or save a signal for future waiters. Check the condition in a while, not an if: another thread may change the state before you reacquire the lock. This is a blocking protocol, not await; the example targets a .NET 8 console, not a browser.

Examples

using System;
using System.Threading;

object gate = new();
bool ready = false;
int result = 0;

var worker = new Thread(() =>
{
    lock (gate)
    {
        result = 42;
        ready = true;
        Monitor.PulseAll(gate);
    }
});

int observed;
lock (gate)
{
    worker.Start();
    while (!ready)
    {
        Monitor.Wait(gate);
    }
    observed = result;
}

worker.Join();
Console.WriteLine($"Result: {observed}");
Console.WriteLine("Worker finished.");

Result

Result: 42
Worker finished.

The main thread calls `Start()` while holding `gate`, so the worker cannot set `ready` until `Wait` releases the lock. After reacquiring it, the main thread reads `result`, exits `lock`, and only then calls `Join()`. The expected lines are `Result: 42` and `Worker finished.`, in that order.

Related lessons

  • C# · Lesson 17 · Advanced · Version: 3

Sources