lock只能使用引用类型,严格来说是需要对象的实例。即使对象在意义上是相同的,但是如果不是ReferenceEquals的话,那么将作为两个实例来对待,那么C# lock 的就不是同一个东西。也就是说,当你以为这个 lock 生效的话,它其实在做无用工。
测试用例:
01 using System;
02 using System.Threading;
03
04 class TTT
05 {
06 private hello test;
07
08 public TTT(hello t)
09 {
10 this.test = t;
11 }
12
13 public void DoTransactions()
14 {
15 lock (test)
16 {
17 for (int i = 0; i < 10; i++)
18 {
19 Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
20 }
21 }
22 }
23 }
24
25
26 class hello
27 {
28 internal int i;
29 }
30
31
32 class Test
33 {
34 static void Main()
35 {
36 Thread[] threads = new Thread[10];
37 //TTT acc = new TTT(new hello()); //启用此处,lock会生效,因为lock的是同一个实例
38 for (int i = 0; i < 10; i++)
39 {
40 TTT acc = new TTT(new hello()); //启用此处,lock不会生效,因为lock的不是同一个实例
41 Thread t = new Thread(new ThreadStart(acc.DoTransactions));
42 threads[i] = t;
43 }
44 for (int i = 0; i < 10; i++)
45 {
46 threads[i].Start();
47 }
48
49 Console.ReadLine();
50 }
51 }