Mutex是可以进程间同步的同步基元。
| 名称 | 说明 | |
|---|---|---|
| Mutex() |
Mutex 类的新实例。 |
|
| Mutex(Boolean) |
Mutex 类的新实例。 |
|
| Mutex(Boolean, String) |
Mutex 类的新实例。 |
|
| Mutex(Boolean, String, Boolean) |
Mutex 类的新实例。 |
|
| Mutex(Boolean, String, Boolean, MutexSecurity) |
Mutex 类的新实例。 |
1 private static Mutex _asyncLocker = new Mutex(); 2 static void Main(string[] args) 3 { 4 MutextDemo mutext = new MutextDemo(); 5 int test = 0; 6 Thread th1 = new Thread(() => 7 { 8 for (int i = 0; i < 100; i++) 9 Add(ref test); 10 }); 11 th1.Name = "T1"; 12 Thread th2 = new Thread(() => 13 { 14 for (int i = 0; i < 100; i++) 15 Add(ref test, 10); 16 }); 17 th2.Name = "T2"; 18 Thread th3 = new Thread(() => 19 { 20 for (int i = 0; i < 100; i++) 21 Add(ref test, 20); 22 }); 23 th3.Name = "T3"; 24 Thread th4 = new Thread(() => 25 { 26 for (int i = 0; i < 100; i++) 27 Add(ref test, 30); 28 }); 29 th4.Name = "T4"; 30 Thread th5 = new Thread(() => 31 { 32 for (int i = 0; i < 100; i++) 33 Add(ref test, 40); 34 }); 35 th5.Name = "T5"; 36 37 th1.Start(); 38 th2.Start(); 39 th3.Start(); 40 th4.Start(); 41 th5.Start(); 42 43 Console.ReadKey(); 44 } 45 46 public static void Add(ref int value, int sleep = 0) 47 { 48 _asyncLocker.WaitOne(); 49 int temp = value; 50 Thread.Sleep(sleep); 51 value = temp + 1; 52 Console.WriteLine($"{Thread.CurrentThread.Name} : {value}"); 53 _asyncLocker.ReleaseMutex(); 54 }