【发布时间】:2013-09-23 21:41:28
【问题描述】:
我的 System.Threading.Timer(它有一个回调)永远不会可靠地触发。这是我的编程任务的一部分,我在其中输入计时器应该从文本框中运行的时间量。
定时器是这样声明的:
System.Threading.Timer timer = new System.Threading.Timer(WorkerObject.callback, null, delay, Timeout.Infinite);
延迟是简单的int 描述回调第一次触发的延迟(它应该只触发一次)。
回调方法是这样的:
public static void callback(Object stateinfo)
{
stop = true;
}
所做的只是将标志设置为 true 以停止循环(由 ThreadPool 上的线程运行,实际上是停止线程)。
循环如下所示:
while (!stop)
{
currentTextbox.Invoke(new Action(delegate()
{
currentTextbox.AppendText((counter++) + Environment.NewLine);
currentTextbox.Update();
}));
}
我的问题是stop 变量对于任何超过 5000 毫秒的延迟始终为假。有没有办法“强制”回调始终触发?
【问题讨论】:
-
这个问题可能不适用(我忘记了 API)...但是你启动计时器了吗?
-
程序只是打印出一个不断递增的计数器,直到计时器停止。 System.Threading.Timer 不需要启动;它会在延迟后自动启动(0 表示没有延迟,但在我的情况下,我指定了延迟)
-
@Jaxidian:
System.Threading.Timer在你创建它时开始。
标签: c# multithreading timer