首先Mutx m = new Mutex();
在一個函數中m.WaitOne();
然後m.ReleaseMutex ();
在另一個函數中同樣m.WaitOne();
m.ReleaseMutex();
你要寫的只能一個行程存取的程式碼段就放在m.WaitOne();和m.ReleaseMutex();中間
private Mutex mutF = new Mutex(); private Mutex mutH = new Mutex(); private void ReadF() { mutF.WaitOne(); // your code to access the resource mutF.ReleaseMutex(); } private void ReadH() { mutH.WaitOne(); // your code to access the resource mutH.ReleaseMutex(); } private void Form1_Load(object sender, EventArgs e) { Thread tF = new Thread(new ThreadStart(ReadF)); Thread tH = new Thread(new ThreadStart(ReadH)); tFlower.Start(); tH.Start(); mutF.WaitOne(); mutH.WaitOne(); // your code to access the resource Thread.Sleep(1000); mutH.ReleaseMutex(); mutF.ReleaseMutex(); }
以上是C#Thread同步Mutex的程式碼詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!