CodeBlanks Logo Icon CodeBlanks

ThreadPool

C# course · Expert · Lesson 21/47

Learn the thread pool with ThreadPool.

ThreadPool

The ThreadPool is a pool of ready threads shared by short tasks in the application. Creating a new Thread each time is costly; the ThreadPool reuses its threads.

ThreadPool.QueueUserWorkItem(callback) enqueues a work item that runs on an idle pool thread. The ThreadPool is not suitable for long work; it can exhaust the pool.

ThreadPool and waiting

There is no guarantee when work enqueued to the ThreadPool will finish. In tests you wait with a signal mechanism such as ManualResetEvent or CountdownEvent.

Production code usually prefers Task.Run; it also uses the ThreadPool but makes waiting easy with await and keeps the code simple.

Exercise ThreadPool with a signal wait

Create a signal with ManualResetEvent done = new ManualResetEvent(false);. Enqueue work with ThreadPool.QueueUserWorkItem(_ => { done.Set(); });. Wait with done.WaitOne();. Finally print Console.WriteLine("Done");.

Show example solution
ManualResetEvent done = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(_ => { done.Set(); }); done.WaitOne(); Console.WriteLine("Done");
Example solution:
using System;
using System.Threading;

class Program
{
    static void Main()
    {
        ManualResetEvent done = new ManualResetEvent(false);
        ThreadPool.QueueUserWorkItem(_ => { done.Set(); });
        done.WaitOne();
        Console.WriteLine("Done");
    }
}

Test yourself

  1. What does ThreadPool.QueueUserWorkItem do?

    • Creates a new thread
    • Cancels a thread
    • Pauses a thread
    • Enqueues a work item
    Show answer

    Enqueues a work item — Correct. QueueUserWorkItem enqueues a work item.

  2. The QueueUserWorkItem call

    ThreadPool.____(state => { /* iş */ });
    Show answer
    ThreadPool.QueueUserWorkItem(state => { /* iş */ });
  3. Match the ThreadPool concepts

    ThreadPool
    Ready thread pool
    QueueUserWorkItem
    Enqueue work
    ManualResetEvent
    Wait with signal
    Task.Run
    ThreadPool + await

All lessons in Expert