I am looking for the best practices to synchronize Tasks (not even sure that this is semantically right, I should probably say synchronize Threads with async code).
Take the following code:
Task.Run(async () => await lib.WaitAsync());
Task.Run(async () => await lib.WaitAsync());
Task.Run(async () => await lib.WaitAsync());
// Synchronize all waiters
lib.Release();
// All Tasks shall be completed
When working with Threads, I used to do that with ManualResetEvent
. So my first (simplified) approach would be:
Task WaitAsync()
{
await Task.Run(() => manualResetEvent.WaitOne());
}
void Release()
{
manualResetEvent.Set();
}
Now I see that people have made their own implementation of async ManualResetEvent
.
What is wrong with the original approach and why would someone prefer an async implementation ? Is it because of the cancellation ? The exceptions unwrapping/handling ?
And more generally, is there any disadvantage when using the regular Thread synchronization objects (Mutex, Semaphore, ...) with async code ?
Thank you