【发布时间】:2013-06-23 17:23:01
【问题描述】:
我在 Richter 的书中看到了这段代码:
以下代码演示了如何进行线程池线程调用 一个方法立即开始,然后每 2 秒开始一次:
/*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*/ }
但是,(对不起),我还是不明白#7,#8是什么意思
当然 - 为什么将它初始化(第 9 行)为 Timeout.Infinite(显然是:“不要启动计时器”)
(我确实了解防止重叠的一般目的,但我相信这里还有一个 GC 竞争条件 pov。)
编辑
命名空间是System.Threading
【问题讨论】:
-
防止第一次执行回调
Status和分配给s_timer之间的竞争,与GC无关。 -
而且它真的很聪明,我永远不会有这样的把戏。感谢杰弗里·里希特!
-
在这种特殊情况下,Sleep(1000) 也会阻止竞争条件。使示例有点做作。
-
@HenkHolterman 为什么它会阻止比赛?如果主线程从未被唤醒,代码也会崩溃。我错过了什么吗?...
标签: c# multithreading .net-4.0 timer