Threads and the thread pool
A Thread is an operating-system thread that a program starts itself. The thread pool is a set of threads the runtime keeps and reuses, and a Task is the unit of work that runs on it. This lesson starts threads directly, which is what a program does when it needs a dedicated thread, and shows what the pool looks like from the inside.
A Thread and Join
Thread.Start begins the thread and Join waits for it to end. The program sets IsBackground before the start, because a background thread does not keep the process alive:
Console.WriteLine("main start");
var thread = new Thread(() =>
{
Console.WriteLine("worker start");
Thread.Sleep(20);
Console.WriteLine("worker end");
})
{
IsBackground = true,
};
var background = thread.IsBackground;
thread.Start();
thread.Join();
Console.WriteLine($"joined {thread.ThreadState}");
Console.WriteLine($"background before {background}");
dotnet run
main start
worker start
worker end
joined Stopped
background before True
The worker printed its two lines while the main thread waited in Join, and the state after the join is Stopped. IsBackground was read before the start into a local, which the next section explains: after the thread ends, the property throws.
Reading a thread that has ended
A Thread object outlives its thread. The properties that describe the running thread are no longer valid once it has stopped, and reading one throws rather than returning an old value:
var worker = new Thread(() => Thread.Sleep(1));
worker.Start();
worker.Join();
try
{
Console.WriteLine($"background after {worker.IsBackground}");
}
catch (ThreadStateException e)
{
Console.WriteLine($"reading after the end {e.GetType().Name}");
Console.WriteLine($"message {e.Message}");
}
Console.WriteLine("after the try");
dotnet run
reading after the end ThreadStateException
message Thread is dead; state cannot be accessed.
after the try
The exception has a name that says what happened: the thread is dead and its state cannot be accessed. ThreadState is the exception to that rule and answers Stopped, which the first program printed. A program that needs the properties of a thread after it ends keeps them in variables before the end, as the first program did.
The thread pool
The pool starts with a minimum number of threads and adds more when the work waits. QueueUserWorkItem puts a callback on it, and the callback runs on a pool thread, which a program can check:
var done = new ManualResetEventSlim();
ThreadPool.QueueUserWorkItem(_ =>
{
Console.WriteLine($"pool thread {Thread.CurrentThread.IsThreadPoolThread}");
done.Set();
});
done.Wait();
ThreadPool.GetMinThreads(out var workers, out var completion);
Console.WriteLine($"min workers {workers}");
Console.WriteLine($"min completion {completion}");
Console.WriteLine($"main is pool {Thread.CurrentThread.IsThreadPoolThread}");
dotnet run
pool thread True
min workers 4
min completion 1
main is pool False
The callback ran on a pool thread, and the main thread is not one. The minimum of the pool is four worker threads and one completion thread here, which follows the four processors of the container. A blocked pool thread is replaced slowly, so a callback that waits for a long time is better written as an async method, which returns its thread to the pool while it waits.
Thread, pool or task
- A Task is the default: it schedules on the pool, composes with await, carries exceptions and a result, and takes a cancellation token.
- A pool callback fits a fire-and-forget piece of work with no result, but it has no way to report an exception to the caller.
- A dedicated Thread fits a long-running loop that owns a resource and must not share a pool thread, and a thread whose apartment state matters on Windows.
- A program that needs a hard limit on concurrency uses SemaphoreSlim with tasks, which the lesson after the next one shows.
Exercises
- Start three threads that print their number after a different sleep and collect the order.
- Read ThreadState before, during and after a thread and print the three values.
- Queue ten work items on the pool and count how many threads ran them.
- Make a foreground thread sleep for a minute and observe whether the process waits for it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which class starts an operating-system thread?
Answer
Thread
Thread.Start begins a new OS thread; Task runs on the pool.
-
What does Thread.Join do?
Answer
Waits until the thread ends
The main thread waited in Join while the worker printed its lines.
-
What does this program print?
var t = new Thread(() => Console.WriteLine("w")); t.Start(); t.Join();Answer
w
The worker prints one line and Join waits for it before the program ends.
-
What does IsBackground = true mean?
Answer
The process does not wait for the thread before it ends
A foreground thread keeps the process alive; a background one does not.
-
What does this program print?
Console.WriteLine(Thread.CurrentThread.IsThreadPoolThread);Answer
False
The main thread is started by the runtime and is not a pool thread, as the measured line showed.
-
Which exception does reading IsBackground of an ended thread throw?
Answer
ThreadStateException
The measured message was "Thread is dead; state cannot be accessed."
-
What does this program print?
var t = new Thread(() => { }); t.Start(); t.Join(); Console.WriteLine(t.ThreadState);Answer
Stopped
The thread ended, and ThreadState is the property that still answers.
-
What does ThreadPool.QueueUserWorkItem do?
Answer
Queues a callback to run on a pool thread
The callback ran on a thread whose IsThreadPoolThread was true.
-
What does this program print?
ThreadPool.GetMinThreads(out var workers, out var completion); Console.WriteLine(workers > 0);Answer
True
The pool has a positive minimum of worker threads, which was four here.
-
Why is a Task preferred over a raw Thread for most work?
Answer
It schedules on the pool and carries results, exceptions and cancellation
A Task composes and reports, while a thread only runs a delegate.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev