You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I created a unit test to try and understand how it works.. I came across a scenario that should work (reread your docs and others for a good 15 minutes).
[Fact]publicasync Task WillWaitForMonitor(){varmonitor=new AsyncMonitor();// 1. Fall through with the delay.varsw= Stopwatch.StartNew();using(await monitor.EnterAsync())await Task.WhenAny(Task.Delay(100), monitor.WaitAsync()).AnyContext();
sw.Stop();
Assert.InRange(sw.ElapsedMilliseconds,100,125);// 2. Wait for the pulse to be set.
sw.Restart();using(await monitor.EnterAsync()){
Task.Run(async()=>{await Task.Delay(50).AnyContext(); Logger.Trace().Message("Pulse").Write(); monitor.Pulse(); Logger.Trace().Message("Pulsed").Write();});
Logger.Trace().Message("Waiting").Write();await monitor.WaitAsync().AnyContext();}
sw.Stop();
Assert.InRange(sw.ElapsedMilliseconds,50,100);}
It outputs
[15:51:59.602 T InMemoryLockTests] Waiting
[15:51:59.654 T InMemoryLockTests] Pulse
[15:51:59.657 T InMemoryLockTests] Pulsed
But the monitor.WaitAsync() never completes and waits for ever. Is there a reason for this?
The text was updated successfully, but these errors were encountered:
Monitor.WaitAsync is a method that changes the underlying state of the monitor. You especially need to be careful when using Task.WhenAny with synchronization primitives (there is almost never a good reason to do this).
In this case, as far as the monitor knows, it has two waiters: the first WaitAsync and the second WaitAsync. So when the Pulse comes through, it satisfies the first task, as it should.
FYI, the unit test for "pulsing a monitor releases a waiter" is here.
On a side note, unit tests that depend on timings are inherently unstable.
I see in your unit tests that you are entering the monitor to pulse. In your docs and my working unit test it doesn't mention that you have to do this. Is this required or just a best practice?
I created a unit test to try and understand how it works.. I came across a scenario that should work (reread your docs and others for a good 15 minutes).
It outputs
But the monitor.WaitAsync() never completes and waits for ever. Is there a reason for this?
The text was updated successfully, but these errors were encountered: