public void CanEnterReadEx() { var x = new ReadWriteLock(); IDisposable engagement = null; try { if (x.TryEnterRead(out engagement)) { Assert.IsFalse(x.IsCurrentThreadWriter); } else { Assert.Fail(); } } finally { if (engagement != null) { engagement.Dispose(); } } }
public void CanReentryWriteToReadEx() { var x = new ReadWriteLock(); IDisposable engagementA = null; try { if (x.TryEnterWrite(out engagementA)) { Assert.IsTrue(x.IsCurrentThreadWriter); IDisposable engagementB = null; try { if (x.TryEnterRead(out engagementB)) { Assert.IsTrue(x.IsCurrentThreadWriter); } else { Assert.Fail(); } } finally { if (engagementB != null) { engagementB.Dispose(); } } } else { Assert.Fail(); } } finally { if (engagementA != null) { engagementA.Dispose(); } } }
public void CanReentryReadToWriteEx() { var x = new ReadWriteLock(false); IDisposable engagementA = null; try { if (x.TryEnterRead(out engagementA)) { Assert.IsFalse(x.IsCurrentThreadWriter); IDisposable engagementB = null; try { if (x.TryEnterWrite(out engagementB)) { Assert.Fail(); } else { // Not reentrant ReadWriteLock will not be able to upgrade the lock Assert.IsFalse(x.IsCurrentThreadWriter); } } finally { if (engagementB != null) { engagementB.Dispose(); } } } else { Assert.Fail(); } } finally { if (engagementA != null) { engagementA.Dispose(); } } // var y = new ReadWriteLock(true); IDisposable engagementC = null; try { if (y.TryEnterRead(out engagementC)) { Assert.IsFalse(y.IsCurrentThreadWriter); IDisposable engagementD = null; try { if (y.TryEnterWrite(out engagementD)) { // Reentrant ReadWriteLock will be able to upgrade the lock Assert.IsTrue(y.IsCurrentThreadWriter); } else { Assert.Fail(); } } finally { if (engagementD != null) { engagementD.Dispose(); } } } else { Assert.Fail(); } } finally { if (engagementC != null) { engagementC.Dispose(); } } }
public void CanReadWhileReadingEx() { var x = new ReadWriteLock(); var ok = true; var doneThread = false; IDisposable engagementA = null; try { if (x.TryEnterRead(out engagementA)) { Assert.IsFalse(x.IsCurrentThreadWriter); var a = new Thread ( () => { IDisposable engagementB = null; try { if (x.TryEnterRead(out engagementB)) { } else { ok = false; } } finally { if (engagementB != null) { engagementB.Dispose(); } doneThread = true; } } ); a.Start(); a.Join(); } } finally { if (engagementA != null) { engagementA.Dispose(); } doneThread = true; } Assert.IsTrue(ok); Assert.IsTrue(doneThread); }
public void CannotReadWhileWriting() { var x = new ReadWriteLock(); var ok = true; var doneThread = false; using (x.EnterWrite()) { Assert.IsTrue(x.IsCurrentThreadWriter); var a = new Thread ( () => { IDisposable engagement = null; try { if (x.TryEnterRead(out engagement)) { ok = false; } } finally { if (engagement != null) { engagement.Dispose(); } doneThread = true; } } ); a.Start(); a.Join(); } Assert.IsTrue(ok); Assert.IsTrue(doneThread); }