implement a thread pool in csharp

Here's an example implementation of a thread pool in C# using the ThreadPool class:

main.cs
using System;
using System.Collections.Generic;
using System.Threading;

public class ThreadPoolExample
{
    // Queue of work items to be processed by the thread pool
    private readonly Queue<Action> workQueue = new Queue<Action>();

    // Semaphore used to signal that there's work to be processed
    private readonly SemaphoreSlim workSignal = new SemaphoreSlim(0);

    // Number of worker threads in the thread pool
    private readonly int threadCount;

    public ThreadPoolExample(int threadCount)
    {
        this.threadCount = threadCount;
    }

    public void QueueWorkItem(Action workItem)
    {
        // Add the work item to the queue
        lock (workQueue)
        {
            workQueue.Enqueue(workItem);
        }

        // Signal the semaphore to wake up a worker thread
        workSignal.Release();
    }

    public void Start()
    {
        // Create the worker threads
        for (int i = 0; i < threadCount; i++)
        {
            Thread thread = new Thread(WorkLoop);
            thread.IsBackground = true;
            thread.Start();
        }
    }

    private void WorkLoop()
    {
        while (true)
        {
            // Wait for a signal from the semaphore
            workSignal.Wait();

            // Try to get a work item from the queue
            Action workItem = null;
            lock (workQueue)
            {
                if (workQueue.Count > 0)
                {
                    workItem = workQueue.Dequeue();
                }
            }

            // If we got a work item, execute it
            if (workItem != null)
            {
                workItem();
            }
        }
    }
}
1681 chars
69 lines

To use this thread pool, you would first create an instance of ThreadPoolExample, passing in the number of worker threads you want in the thread pool. You can then add work items to the thread pool by calling the QueueWorkItem method with an Action representing the work to be done. Finally, you would start the thread pool by calling the Start method, which creates the worker threads and starts the WorkLoop method running in each thread.

gistlibby LogSnag