Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awaitable AutoResetEvent

What would be the async (awaitable) equivalent of AutoResetEvent?

If in the classic thread synchronization we would use something like this:

    AutoResetEvent signal = new AutoResetEvent(false);      void Thread1Proc()     {         //do some stuff         //..         //..          signal.WaitOne(); //wait for an outer thread to signal we are good to continue          //do some more stuff         //..         //..     }      void Thread2Proc()     {         //do some stuff         //..         //..          signal.Set(); //signal the other thread it's good to go          //do some more stuff         //..         //..     } 

I was hoping that in the new async way of doing things, something like this would come to be:

SomeAsyncAutoResetEvent asyncSignal = new SomeAsyncAutoResetEvent();  async void Task1Proc() {     //do some stuff     //..     //..      await asyncSignal.WaitOne(); //wait for an outer thread to signal we are good to continue      //do some more stuff     //..     //.. }  async void Task2Proc() {     //do some stuff     //..     //..      asyncSignal.Set(); //signal the other thread it's good to go      //do some more stuff     //..     //.. } 

I've seen other custom made solutions, but what I've managed to get my hands on, at some point in time, still involves locking a thread. I don't want this just for the sake of using the new await syntax. I'm looking for a true awaitable signaling mechanism which does not lock any thread.

Is it something I'm missing in the Task Parallel Library?

EDIT: Just to make clear: SomeAsyncAutoResetEvent is an entirely made up class name used as a placeholder in my example.

like image 652
Mihai Caracostea Avatar asked Sep 18 '15 14:09

Mihai Caracostea


People also ask

What is AutoResetEvent?

AutoResetEvent remains signaled until a single waiting thread is released, and then automatically returns to the non-signaled state. If no threads are waiting, the state remains signaled indefinitely. If a thread calls WaitOne while the AutoResetEvent is in the signaled state, the thread does not block.

What is WaitHandle in C#?

WaitAny(WaitHandle[], TimeSpan, Boolean) Waits for any of the elements in the specified array to receive a signal, using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait. WaitOne() Blocks the current thread until the current WaitHandle receives a signal.


1 Answers

If you want to build your own, Stephen Toub has the definitive blog post on the subject.

If you want to use one that's already written, I have one in my AsyncEx library. AFAIK, there's no other option as of the time of this writing.

like image 178
Stephen Cleary Avatar answered Sep 25 '22 08:09

Stephen Cleary