C#Thread同步Mutex的代码详解


本文摘自PHP中文网,作者黄舟,侵删。

首先Mutx m = new Mutex();

在一个函数中 m.WaitOne();

然后 m.ReleaseMutex();

在另一个函数中 同样 m.WaitOne();

m.ReleaseMutex();

你要写的只能一个进程访问的代码段就放在m.WaitOne();和m.ReleaseMutex();中间

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

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的代码详解的详细内容!

相关阅读 >>

C#thread同步mutex的代码详解

C#中将字符串内容写入到txt文件中

C#控制台应用程序中如何输出彩色字体的详细介绍

具体介绍使用C#访问access数据库时,提示找不到可安装的isam(图)

分享125个基本的C#面试问答

C#字符串处理小工具的详细介绍

C#怎么学

c#中的arraylist是什么?

浅谈C# 之 hashtable 与 dictionary的代码实例

C#中list的用法

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...