11.5.10

mail@pastecode.io avatar
unknown
csharp
a year ago
933 B
0
Indexable
Never
using System;
using System.Collections.Concurrent;
using System.Threading;

public class CustomThreadPool
{
    private readonly BlockingCollection<Action> _queue = new BlockingCollection<Action>();
    private readonly Thread[] _threads;

    public CustomThreadPool(int threadCount)
    {
        _threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++)
        {
            _threads[i] = new Thread(() =>
            {
                foreach (var action in _queue.GetConsumingEnumerable())
                {
                    action();
                }
            });
            _threads[i].Start();
        }
    }

    public void Enqueue(Action action)
    {
        _queue.Add(action);
    }

    public void Shutdown()
    {
        _queue.CompleteAdding();
        foreach (var thread in _threads)
        {
            thread.Join();
        }
    }
}