public void Enter(ref bool lockTaken)
{
if (lockTaken)
throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
throw new LockRecursionException ();
int slot = -1;
RuntimeHelpers.PrepareConstrainedRegions ();
try {
slot = Interlocked.Increment (ref ticket.Users) - 1;
SpinWait wait = new SpinWait ();
while (slot != ticket.Value) {
wait.SpinOnce ();
while (stallTickets != null && stallTickets.TryRemove (ticket.Value))
++ticket.Value;
}
} finally {
if (slot == ticket.Value) {
lockTaken = true;
threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
} else if (slot != -1) {
// We have been interrupted, initialize stallTickets
if (stallTickets == null)
Interlocked.CompareExchange (ref stallTickets, new ConcurrentOrderedList<int> (), null);
stallTickets.TryAdd (slot);
}
}
}
private static void Main(string[] args) { SpinLock slock = new SpinLock(false); long sum1 = 0; long sum2 = 0; Parallel.For(0, 10000, i => { sum1 += i; }); Parallel.For(0, 10000, i => { bool lockTaken = false; try { slock.Enter(ref lockTaken); sum2 += i; } finally { if (lockTaken) slock.Exit(false); } }); Console.WriteLine("Num1的值为:{0}", sum1); Console.WriteLine("Num2的值为:{0}", sum2); }