本文整理汇总了C#中System.Threading.ReaderWriterLockSlim.UsingWriteLock方法的典型用法代码示例。如果您正苦于以下问题:C# ReaderWriterLockSlim.UsingWriteLock方法的具体用法?C# ReaderWriterLockSlim.UsingWriteLock怎么用?C# ReaderWriterLockSlim.UsingWriteLock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.ReaderWriterLockSlim
的用法示例。
在下文中一共展示了ReaderWriterLockSlim.UsingWriteLock方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestReadWriteLockSlim
public void TestReadWriteLockSlim()
{
var sentry = new ReaderWriterLockSlim();
var sw = new Stopwatch();
sw.Start();
var barrier = new CountdownEvent(4);
//first read
ThreadPool.QueueUserWorkItem(_ =>
{
using (sentry.UsingReadLock())
{
Console.WriteLine("Acquired read: {0}ms, thread={1}", sw.ElapsedMilliseconds,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
Console.WriteLine("Releasing read: {0}ms, thread={1}", sw.ElapsedMilliseconds,
Thread.CurrentThread.ManagedThreadId);
}
barrier.Signal();
});
//write
ThreadPool.QueueUserWorkItem(_ =>
{
Thread.Sleep(100);
using (sentry.UsingWriteLock())
{
Console.WriteLine("Acquired write: {0}ms, thread={1}", sw.ElapsedMilliseconds,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
Console.WriteLine("Releasing write: {0}ms, thread={1}", sw.ElapsedMilliseconds,
Thread.CurrentThread.ManagedThreadId);
}
barrier.Signal();
});
//read that starts after write but executes before
ThreadPool.QueueUserWorkItem(_ =>
{
Thread.Sleep(200);
using (sentry.UsingReadLock())
{
Console.WriteLine("Acquired read: {0}ms, thread={1}", sw.ElapsedMilliseconds,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
Console.WriteLine("Releasing read: {0}ms, thread={1}", sw.ElapsedMilliseconds,
Thread.CurrentThread.ManagedThreadId);
}
barrier.Signal();
});
//this read task must wait for write on
ThreadPool.QueueUserWorkItem(_ =>
{
Thread.Sleep(1000);
using (sentry.UsingReadLock())
{
Console.WriteLine("Acquired read: {0}ms, thread={1}", sw.ElapsedMilliseconds,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
Console.WriteLine("Releasing read: {0}ms, thread={1}", sw.ElapsedMilliseconds,
Thread.CurrentThread.ManagedThreadId);
}
barrier.Signal();
});
barrier.Wait();
sw.Stop();
Console.WriteLine("Test finished");
}