lock 关键字将语句块标记为临界区, 方法是获取给定对象的互斥锁, 执行语句, 然后释放该锁.
lock 关键字可确保当一个线程位于代码的临界区时, 另一个线程不会进入该临界区. 如果其他线程尝试进入锁定的代码, 则它将一直等待 (即被阻止), 直到该对象被释放.
lock 关键字在块的开始处调用 Enter, 而在块的结尾处调用 Exit. ThreadInterruptedException 引发, 如果 Interrupt 中断等待输入 lock 语句的线程.
通常, 应避免锁定 public 类型, 否则实例将超出代码的控制范围.
常见的结构 lock (this),lock (typeof (MyType)) 和 lock ("myLock") 违反此准则:
如果实例可以被公共访问, 将出现 lock (this) 问题.
如果 MyType 可以被公共访问, 将出现 lock (typeof (MyType)) 问题.
由于进程中使用同一字符串的任何其他代码都将共享同一个锁, 所以出现 lock("myLock") 问题.
最佳做法是定义 private 对象来锁定, 或 private static 对象变量来保护所有实例所共有的数据.
在 lock 语句的正文不能使用 等待 关键字
1,lock 的是引用类型的对象, string 类型除外.
2,lock 推荐的做法是使用静态的, 只读的, 私有的对象.
3, 保证 lock 的对象在外部无法修改才有意义, 如果 lock 的对象在外部改变了, 对其他线程就会畅通无阻, 失去了 lock 的意义.
- using System;
- using System.Threading;
- namespace Chapter1.Recipe9
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Incorrect counter");
- var c = new Counter();
- var t1 = new Thread(() => TestCounter(c));
- var t2 = new Thread(() => TestCounter(c));
- var t3 = new Thread(() => TestCounter(c));
- t1.Start();
- t2.Start();
- t3.Start();
- t1.Join();
- t2.Join();
- t3.Join();
- Console.WriteLine("Total count: {0}", c.Count);
- Console.WriteLine("--------------------------");
- Console.ReadKey();
- Console.WriteLine("Correct counter");
- var c1 = new CounterWithLock();
- t1 = new Thread(() => TestCounter(c1));
- t2 = new Thread(() => TestCounter(c1));
- t3 = new Thread(() => TestCounter(c1));
- t1.Start();
- t2.Start();
- t3.Start();
- t1.Join();
- t2.Join();
- t3.Join();
- Console.WriteLine("Total count: {0}", c1.Count);
- Console.ReadKey();
- }
- static void TestCounter(CounterBase c)
- {
- for (int i = 0; i < 100000; i++)
- {
- c.Increment();
- c.Decrement();
- }
- }
- class Counter : CounterBase
- {
- public int Count { get; private set; }
- public override void Increment()
- {
- Count++;
- }
- public override void Decrement()
- {
- Count--;
- }
- }
- class CounterWithLock : CounterBase
- {
- private static readonly object _syncRoot = new Object();
- public int Count { get; private set; }
- public override void Increment()
- {
- lock (_syncRoot)
- {
- Count++;
- }
- }
- public override void Decrement()
- {
- lock (_syncRoot)
- {
- Count--;
- }
- }
- }
- abstract class CounterBase
- {
- public abstract void Increment();
- public abstract void Decrement();
- }
- }
- }
- View Code
来源: http://www.bubuko.com/infodetail-2654702.html