C#Thread同步Mutex的代码详解
程序员文章站
2022-05-01 12:15:26
...
首先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的代码详解的详细内容,更多请关注其它相关文章!