Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a nonblocking wait handle?

Essentially, what I'm doing is creating a web server to handle an API call, and then when it's done continue the method execution, so essentially:

new WebServer(myAutoResetEvent);
myAutoResetEvent.WaitOne();

However, this blocks the thread until then. Is there any way to make this async? Is it fine just to wrap it in a await Task.Run() call, i.e. await Task.Run(() => myAutoResetEvent.WaitOne())?

Thanks!

like image 291
It'sNotALie. Avatar asked Feb 08 '23 04:02

It'sNotALie.


1 Answers

Normally, the WebServer ctor should not do anything interesting. There should be a Task WebServer.RunAsync function that runs the server. You can then use the resulting task to synchronize and coordinate.

If you don't want that you can use a TaskCompletionSource<object> as a one-shot async-ready event.

I believe the ThreadPool class has a way to efficiently wait for a WaitHandle to be set but that's a worse solution.

like image 98
usr Avatar answered Feb 11 '23 18:02

usr