readonly object _Syn = new object(); int Seed = 0; public int TreadValueGet() { // 5 Critical Section // Enter 和 Exit 方法提供的功能与 C# lock 语句提供的功能相同, // 区别在于 lock 将 Enter(Object, Boolean) 方法重载和 Exit 方法包装在 try…finally 块中以确保释放监视器 //int _retValue = 0; //while (!System.Threading.Monitor.TryEnter(_Syn, 2))//TryEnter可以防御线程死锁 //{ //} //try //{ // _retValue = Seed + 1; // Seed = _retValue; // return _retValue; //} //finally //{ // System.Threading.Monitor.Exit(_Syn); //} // 4 return System.Threading.Interlocked.Increment(ref Seed); // 3 //return System.Threading.Interlocked.Add(ref Seed, 1); // 2 乐观锁,判断旧值未被修改后,用新值替换旧值. // Interlocked.CompareExchange提供原子性的比较替换操作 //int _seed; //int _retValue = 0; //do //{ // _seed = Seed; // _retValue = _seed + 1; //} while (_seed != System.Threading.Interlocked.CompareExchange(ref Seed, _retValue, _seed)); //return _retValue; // 1 最常用方法 //lock (_Syn) //{ // return Seed++; //} }
System.Threading.Interlocked资料
http://msdn.microsoft.com/zh-cn/library/system.threading.interlocked.aspx