After any one thread calls _barrier.SignalAndWait () method performs a callback function to print out phase.
1 /// <summary> 2 /// 实例 Barrier 类 3 /// </summary> 4 public static Barrier _barrier = new Barrier(2, b => Console.WriteLine($"第 {b.CurrentPhaseNumber + 1} 阶段结束")); 5 6 /// <summary> 7 /// 向 Barrier 发送信号 8 /// </summary> 9 /// <param name="name"></param> 10 /// <param name="message"></param> 11 /// <param name="seconds"></param> 12 public static void PlayMusic(string name, string message, int seconds) 13 { 14 for (int i = 1; i < 3; i++) 15 { 16 Console.WriteLine("------------------------"); 17 18 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(seconds)); 19 Console.WriteLine($"{name} 开始 {message}"); 20 21 is System.Threading.Thread.Sleep (TimeSpan.FromSeconds (seconds The)); 22 is Console.WriteLine ($ " {name}} End Message { " ); 23 is 24 // callback function to print out phase 25 _barrier.SignalAndWait (); 26 } 27 }
Barrier each thread will send two signals, so there will be two stages, you can do some calculations before the end of each iteration. You can interact at the end of the iteration when the last thread calls SignalAndWait method.
. 1 /// <Summary> 2 /// executed . 3 /// </ Summary> . 4 public static void Implement () . 5 { . 6 var T1 = new new the System.Threading.Thread (() => PlayMusic ( " guitar " , " concerto " , . 5 )); . 7 . 8 var T2 = new new the System.Threading.Thread (() => PlayMusic ( " artist " , " sing songs he " , 2 )); 9 10 t1.Start(); 11 t2.Start(); 12 }
Output: