永远不会调用System.Threading.Timer回调

doc*_*lic 3 c# multithreading timer

我的System.Threading.Timer(有一个回调)永远不会可靠地触发.这是我的编程任务的一部分,我输入计时器应该从文本框运行的时间量.

计时器声明如下:

System.Threading.Timer timer = new System.Threading.Timer(WorkerObject.callback, null, delay, Timeout.Infinite);
Run Code Online (Sandbox Code Playgroud)

而延迟只是int描述第一次触发回调的延迟(它只能触发一次).

回调方法是这样的:

 public static void callback(Object stateinfo)
 {
     stop = true;
 }
Run Code Online (Sandbox Code Playgroud)

所有这一切都设置了一个标志为true,它停止循环(由ThreadPool上的线程运行,实际上,停止线程).

循环看起来像这样:

while (!stop)
{
    currentTextbox.Invoke(new Action(delegate()
    {
        currentTextbox.AppendText((counter++) + Environment.NewLine);
        currentTextbox.Update();
     }));
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,stop对于超过5000毫秒的任何延迟,变量总是为假.有没有办法"强迫"回调始终开火?

ang*_*son 10

您需要保持对计时器的引用.

很可能是定时器对象被垃圾收集,它将运行其终结器,停止计时器.

因此,只要您需要定时器处于活动状态,请继续参考.


Jim*_*hel 5

我建议使用CancellationTokenSource

static CancellationTokenSource Cancel = new CancellationTokenSource();

public static void Callback(object state)
{
    Cancel.Cancel();
}
Run Code Online (Sandbox Code Playgroud)

和你的循环:

while (!Cancel.IsCancellationRequested)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

这比使用volatile更简洁,并且当您将简单的概念证明移动到单独的类时更容易移植。有关更多信息,请参阅我的博客Polling for Cancellation