1 internal sealed class SimpleSpinLock
2 {
3 //0等于false(默认),1等于true
4 private int m_ResourceInUse = 0;
5
6 public void Enter()
7 {
8 while (true)
9 {
10 //总是将资源设置为正在使用(等于1)
11 //资源未使用(等于0)时返回(不再“自旋”,结束等待,开始执行后续任务)
12 //默认是0,第一个执行的线程会直接return,然后执行Enter后面的代码
13 if (Equals(Interlocked.Exchange(ref m_ResourceInUse, 1), 0))
14 {
15 return;
16 }
17 }
18 }
19
20 public void Leave()
21 {
22 //将资源标记为“未使用”(释放资源)
23 Volatile.Write(ref m_ResourceInUse, 0);
24 }
25 }
26
27 public sealed class SomeResource
28 {
29 private SimpleSpinLock spinLock = new SimpleSpinLock();
30
31 public void AccessResource()
32 {
33 spinLock.Enter();
34
35 //访问资源,一次只能有一个线程
36
37 spinLock.Leave();
38 }
39 }