AutoResetEvent Class in C#

Sau đây là một ví dụ về AutoResetEvent kế thừa EventWaitHandle và nằm trong System.Threading

internal class Program
 {
     private static AutoResetEvent _AutoRestEvent = new(false); // Ban đầu khởi tạo không có tín hiệu
     static void Main()
     {
         Console.WriteLine("Main Thread Start !\n");

         Thread secondThraed = new(new ThreadStart(SecondThreadMethod)); // tạo thread mới có tên secondThread
         secondThraed.Start(); // bắt đầu khởi chạy sencondThread

         _AutoRestEvent.WaitOne(); // chờ sự kiện _AutoRestEvent kích hoạt tín hiệu ở secondThread

         Console.WriteLine("Main Thread continue !");
         // Tạo một hoạt động ở Thread thứ 1 (main Thread)
         for (int i = 5; i > 0; i--) // 5 giây đếm ngược 
         {
             Console.WriteLine($"Main Thread: {i} s");
             Thread.Sleep(1000);
         }

         Console.WriteLine("Main Thread finish !");
         Console.ReadKey();  
     }

     private static void SecondThreadMethod()
     {
         Console.WriteLine("SecondThread Start !");

         // Tạo một hoạt động ở Thread thứ 2 (sencondThread)
         for (int i = 5; i > 0; i--) // 5 giây đếm ngược 
         {
             Console.WriteLine($"Second Thread: {i} s");
             Thread.Sleep(1000);
         }

         Console.WriteLine("secondThread Finish !\n");

         _AutoRestEvent.Set(); // thông báo cho MainThread tiếp tục sau WaitOne();
     }
 }
 
Lưu ý:
+ AutoResetEvent là một sự kiện được tự động reset, có nghĩa là sau khi kích hoạt tín hiệu thì nó sẽ tự động trở về trạng thái chờ cho sự kích hoạt Set() lần tiếp theo
+ Phù hợp cho việc đồng độ hoá giữa các Thread, các thread phối hợp chờ nhau để hoạt động
+ Ứng dụng trong việc chờ một thread có dữ liệu hoặc một tác vụ hoàn thành

Post a Comment

Previous Post Next Post