Search code examples
c#multithreadingwaithandle

How to substitute at runtime the WaitHandle that a thread should wait on


I'm wondering how to safely change at runtime the EventWaitHandle that a thread should wait on.

Suppose for instance that there are two threads (A and C) that are synchronized through EventWaitHandles. A does its job cyclically and C waits until it receives notification from A that it can start doing its job (e.g. by the AutoResetEvent). The pattern is A-C-A-C...

Later on a new thread (B) is launched (e.g. by user action) and its job should be executed in between the two preexistent threads in this way: A makes its job, then signals B and once B finishes it signals C. Now the pattern is A-B-C-A-B-C...

So before thread C was waiting on the EventWaitHandle shared with A and later there should be a safe mechanism that makes C waiting on another EventWaitHandle shared with B. It seems to me that the tricky part is substituting the EventWaitHandle used by C, since once this is done I should easily be able to launch B that will use a EventWaitHandle to wait on A job and a EventWaitHandle to signal for C job. The mechanism should also provide a way to safely unmount thread B and to go back to the initial situation where only thread A and C are working.

Is there a safe way to accomplish this with EventWaitHandle ? If not, any other suggestion would be appreciated.


Solution

  • If task A knows about the change, then have task C own the event. Task A signals task C's event if C is to be next, or task B's event if task B is to be next.

    Alternatively, use the same mechanism as for changing any other shared data: acquire a mutex across all accesses to the handle. e.g. task C acquires the lock, reads the handle, releases the lock, waits on the handle. To change it you have the UI thread acquire the lock, change the handle, release the lock.