1 /// <summary> 2 /// 调用Volatile.Write来写入最后一个值 3 /// 调用Volatile.Read来读取第一个值 4 /// </summary> 5 internal sealed class ThreadsSharingData 6 { 7 private int m_flag = 0; 8 9 private int m_value = 0; 10 11 //线程1 12 public void Thread1() 13 { 14 m_value = 5; 15 16 //在将1写入m_flag之前,必须先将5写入m_value 17 Volatile.Write(ref m_flag, 1); 18 } 19 20 //线程2 21 public void Thread2() 22 { 23 //m_value必然在读取了m_flag之后读取 24 if (Volatile.Read(ref m_flag) == 1) 25 { 26 Console.WriteLine(m_value); 27 } 28 } 29 }