我们初识多线程或者多任务时,第一个想到的同步方法就是使用lock或者Monitor,然而在4.0 之后微软给我们提供了另一把利器——spinLock,它比重量级别的Monitor具有更小的性能开销,它的用法跟Monitor很相似;
下面我们来写一个例子看一下,代码如下(关于lock和Monitor的用法就不再细说了,网上资料很多,大家可以看看):
1 SpinLock slock = new SpinLock(false); 2 long sum1 = 0; 3 long sum2 = 0; 4 Parallel.For(0, 100000, i => 5 { 6 sum1 += i; 7 }); 8 9 Parallel.For(0, 100000, i => 10 { 11 bool lockTaken = false; 12 try 13 { 14 slock.Enter(ref lockTaken); 15 sum2 += i; 16 } 17 finally 18 { 19 if (lockTaken) 20 slock.Exit(false); 21 } 22 }); 23 24 Console.WriteLine("Num1的值为:{0}", sum1); 25 Console.WriteLine("Num2的值为:{0}", sum2); 26 27 Console.Read();