How to signal only one thread to wake up per event

c#, multithreading

Solution

Create multiple instances of `ManualResetEvent`, one for each `Thread` and use `ManualResetEvent.WaitOne()` in each `Thread`, e.g.

public void StartThreadA()
{
    _mreA = new ManualResetEvent();
    _threadA = new Thread(new ThreadStart(() => 
    {
        _mreA.WaitOne();
        // Continue
    });
}

When your even happens you can then handle it like so:

private void OnSomeEvent()
{
   _mreA.Set();
}

This is very limited in terms of scale, if you intend to use a large number of threads, I would suggest using a dictionary to look-up the `ManualResetEvent` for each thread.

Update

As I am now aware you are using a queue of threads I would do something like the following:

private Queue<ManualResetEvent> _queuedThreads = new Queue<ManualResetEvent>();

public void EnqueueThread()
{
    var mre = new ManualResetEvent();
    var thread = new Thread(new ThreadStart(() =>
    {
        mre.WaitOne();
        // Continue
    });

   _queuedThreads.Enqueue(mre);
}

private void OnEvent()
{
    var mre = _queuedThreads.Dequeue();
    mre.Set();   
}

Problem

What I want to do I want to create some threads, say thread A, B, C, and block them until an event occurs. When an event occurs, I want to release only one thread. For Example: ``` Before event occurs: Thread A : blocked Thread B : blocked Thread C : blocked After event occurs: Thread A : blocked Thread B : unblocked THread C : blocked ``` I read that `AutoResetEvent` can do this but I can't specify which thread to be unlocked, and `ManualResetEvent` will unblock all the blocked threads. Is there a way to achieve what I want to do?

Original source

Related problems