andrey1567
andrey1567

Reputation: 139

AutoResetEvent number of waiting threads .net 5.0

I am using AutoResetEvent. I just need to know is it possible to get number of waiting threads?

if (WaitHandler.Reset())
{
     if (WaitHandler.WaitOne(WaitMilliseconds))
     {
         // do something after WaitHandler.Set()  
     }
}

I need to know how many threads are currently waiting in WaitOne(). And is it possible to limit them, like 10 threads max - all other threads throw back? If not - how to limit it?

Upvotes: 1

Views: 296

Answers (1)

Victor Procure
Victor Procure

Reputation: 883

I'm not sure if this is helpful, I found it at https://kmyr.dev/post/limiting-the-number-of-threads

internal sealed class ThreadManager
{
private readonly WaitHandle[] _syncObjects;

public ThreadManager() : this(Environment.ProcessorCount)
{
}

public ThreadManager(int maxThreads)
{
    MaxThreads = maxThreads;

    _syncObjects = new WaitHandle[maxThreads];
    for (var i = 0; i < maxThreads; i++)
    {
        _syncObjects[i] = new AutoResetEvent(true);
    }
}

public int MaxThreads { get; private set; }

public bool StartTask(Action action, bool wait)
{
    var timeout = wait ? Timeout.Infinite : 0;
    var freeIndex = WaitHandle.WaitAny(_syncObjects, timeout);
    if (freeIndex == WaitHandle.WaitTimeout)
    {
        return false;
    }

    ThreadPool.QueueUserWorkItem(
        state =>
            {
                action();
                ((AutoResetEvent)state).Set();
            },
        _syncObjects[freeIndex]);

    return true;
}
}

Upvotes: 1

Related Questions