sharedata.cs

来自「这是.net2005学习不可缺少的教程」· CS 代码 · 共 57 行

CS
57
字号
using System;
using System.Threading;

namespace TestSynchronized
{
	/// <summary>
	/// ShareData 的摘要说明。
	/// </summary>
	public class ShareData
	{
		private int _data;
		private bool state=false;

		public int data
		{
			set
			{
				Monitor.Enter(this);

				if(state)
				{
					Monitor.Wait(this);
				}
				
				Console.WriteLine(Thread.CurrentThread.Name+" put a data is {0}",value);
				this._data=value;

				state=!state;
				Monitor.Pulse(this);
				//Monitor.Wait(this);

				Monitor.Exit(this);
			}
			get
			{
				Monitor.Enter(this);

				if(!state)
				{
					Monitor.Wait(this);
				}

				Console.WriteLine(Thread.CurrentThread.Name+" get a data is {0}",_data);
				

				state=!state;

				Monitor.Pulse(this);

				Monitor.Exit(this);
//				
				return this._data;
			}
		}
	}
}

⌨️ 快捷键说明

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