Closed timcassell closed 1 year ago
After testing Monitor.Wait
, I found that my assumption was only half-true. Running this test, it randomly returns true
or false
. After looking into why, it seems that's due to the granularity of the system clock. According to the documentation, it should always return false
if timeout is 0
, but due to the system clock, it may return true
.
[Test]
public void Monitor_WaitPulse()
{
var mutex = new object();
var promise = Promise.Run(() =>
{
lock (mutex)
{
Monitor.Pulse(mutex);
}
Thread.Sleep(100);
lock (mutex)
{
Monitor.Pulse(mutex);
}
}, SynchronizationOption.Background, forceAsync: true);
lock (mutex)
{
Monitor.Wait(mutex);
}
lock (mutex)
{
Thread.Sleep(1000);
Assert.True(Monitor.Wait(mutex, 0));
}
promise.WaitWithTimeout(TimeSpan.FromSeconds(1));
}
So, I will close this as working as intended.
If the token is already canceled, the lock should be released, then re-enter the lock queue, in case another part of code is already waiting to acquire the lock, in which case the wait should receive the signal and return true. The behavior should match
Monitor.Wait(obj, 0)
; This test fails: