Search code examples
c#wpfautoreseteventwaithandle

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!


Solution

  • 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.