sample52.cs

来自「C#函数手册」· CS 代码 · 共 69 行

CS
69
字号
namespace apiBook
{
	using System;
	using System.Threading;
	public class TestClass 
	{
		static int  num = 10;
		static AutoResetEvent autoResetEvent = new AutoResetEvent(false);
		static TestRWL test = new TestRWL();
		public static void Main() 
		{
			for (int i = 0; i <num; i++) 
			{
				ThreadPool.QueueUserWorkItem(new WaitCallback(UpdateInfo), i);
			}
			autoResetEvent.WaitOne();
			Console.WriteLine("所有线程执行完毕。");
			Console.ReadLine();
		}
		static void UpdateInfo(Object obj) 
		{
			int count = (int) obj;
			if ((count % 2) != 0) test.Read(count);
			else test.Write(count);
			if (Interlocked.Decrement(ref num) == 0)
				autoResetEvent.Set();
		}
	}
	class TestRWL 
	{
		ReaderWriterLock testR = new ReaderWriterLock();

		public void Read(int i) 
		{
			testR.AcquireReaderLock(Timeout.Infinite);
			try 
			{
				Console.WriteLine("开始读线程:"+ i);
				Thread.Sleep(100);
				Console.WriteLine("停止读线程:"+ i);
				
			}
			finally 
			{
				testR.ReleaseReaderLock();	
				//使用ReleaseReaderLock方法释放阅读器锁
			}
		}

		public void Write(int i) 
		{
			testR.AcquireWriterLock(Timeout.Infinite);
			//使用AcquireWriterLock方法获取编写器锁
			try 
			{
				Console.WriteLine("开始写线程:"+i);
				Thread.Sleep(200);
				Console.WriteLine("停止写线程:"+i);
			}
			finally 
		
			{
				testR.ReleaseWriterLock();
				//使用ReleaseWriterLock方法释放编写器锁
			}
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?