tôi thấy mã này vào cuốn sách Richter:Khởi tạo hẹn giờ và điều kiện Race trong C#?
Đoạn mã dưới đây trình bày cách để có một thread hồ bơi gọi một phương pháp bắt đầu ngay lập tức và sau đó mỗi 2 giây sau đó:
/*1*/ internal static class TimerDemo
/*2*/ {
/*3*/ private static Timer s_timer;
/*4*/ public static void Main()
/*5*/ {
/*6*/ Console.WriteLine("Checking status every 2 seconds");
/*7*/ // Create the Timer ensuring that it never fires. This ensures that
/*8*/ // s_timer refers to it BEFORE Status is invoked by a thread pool thread
/*9*/ s_timer = new Timer(Status, null, Timeout.Infinite, Timeout.Infinite);
/*10*/ // Now that s_timer is assigned to, we can let the timer fire knowing
/*11*/ // that calling Change in Status will not throw a NullReferenceException
/*12*/ s_timer.Change(0, Timeout.Infinite);
/*13*/ Console.ReadLine(); // Prevent the process from terminating
/*14*/ }
/*15*/ // This method's signature must match the TimerCallback delegate
/*16*/ private static void Status(Object state)
/*17*/ {
/*18*/ // This method is executed by a thread pool thread
/*20*/ Console.WriteLine("In Status at {0}", DateTime.Now);
/*21*/ Thread.Sleep(1000); // Simulates other work (1 second)
/*22*/ // Just before returning, have the Timer fire again in 2 seconds
/*23*/ s_timer.Change(2000, Timeout.Infinite);
/*24*/ // When this method returns, the thread goes back
/*25*/ // to the pool and waits for another work item
/*26*/ }
/*27*/ }
Tuy nhiên , (xin lỗi), tôi vẫn không hiểu dòng nào #7,#8
nghĩa là
Và dĩ nhiên - tại sao nó được khởi tạo (dòng # 9) thành Timeout.Infinite
(Mà rõ ràng là: "không bắt đầu hẹn giờ")
(Tôi làm hiểu được mục đích chung để ngăn ngừa sự chồng chéo, nhưng tôi tin rằng đó cũng là một
GC
đua điều kiện pov ở đây.)
chỉnh sửa
không gian tên là System.Threading
Để ngăn chặn cuộc gọi giữa lần gọi lại 'Trạng thái' được thực hiện lần đầu tiên và gán cho' s_timer', nó không liên quan đến GC. – Lee
Và nó thực sự thông minh, tôi sẽ không bao giờ có mặc dù để thủ đoạn như vậy. Kudos để * Jeffrey Richter *! – Pragmateek
@Lee edited .... –