public void TestMethod1() { ReaderWriterLockHelper readerWriterLock = new ReaderWriterLockHelper(); AutoResetEvent autoResetEvent = new AutoResetEvent(false); int threadNumber = 3; int value = 10000; new Thread(() => { while (true) { bool needBreak = false; readerWriterLock.Read(() => { if (value <= 0) { needBreak = true; return; } Console.WriteLine($"线程 {Thread.CurrentThread.Name} 计数 {value}"); }); if (needBreak) { break; } } threadNumber--; if (threadNumber <= 0) { autoResetEvent.Set(); } }) { Name = "读" }.Start(); new Thread(() => { while (true) { bool needBreak = false; readerWriterLock.Write(() => { if (value <= 0) { needBreak = true; return; } value--; Console.WriteLine($"线程 {Thread.CurrentThread.Name} 计数 {value}"); }); if (needBreak) { break; } } threadNumber--; if (threadNumber <= 0) { autoResetEvent.Set(); } }) { Name = "写" }.Start(); new Thread(() => { while (true) { if (!readerWriterLock.TryEnterReadLock()) { continue; } try { if (!readerWriterLock.TryEnterWriteLock(out ReaderWriterLockCookie cookie)) { continue; } try { if (value <= 0) { break; } value--; Console.WriteLine($"线程 {Thread.CurrentThread.Name} 计数 {value}"); } finally { readerWriterLock.ExitWriteLock(ref cookie); } } finally { readerWriterLock.ExitReadLock(); } } threadNumber--; if (threadNumber <= 0) { autoResetEvent.Set(); } }) { Name = "读写" }.Start();