C# Thread 同步 Mutex

首先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(); }