c# - System.Threading.Timer 没有启动?

标签 c# timer freeze compact-framework2.0

我将 C# 与 Compact Framework 2, SP2 结合使用。

设备的操作系统已设置为随我的应用程序一起启动,我们将该应用程序称为“Loader.exe”。

Loader 很简单:一个单一的、纯形式,在整个加载过程中显示状态消息,如果有必要(外行术语是出现错误和异常消息,或“正在启动应用程序 [xyz]”),以及一个正在运行的状态机在后台显示基本的全屏表单。

所以 Loader 的表单的构造函数在非常 端有以下内容:

try
{
    label1.Text = "Starting GUI Init Thread...";  //debug only message
    System.Threading.Timer guiInit = new System.Threading.Timer(
        RunStateMachine, null, 2000, System.Threading.Timeout.Infinite
        );
    //callback: RunStateMachine, null argument
    //initial callback is 2000ms from this point, and doesn't run again.
}
catch (Exception ex1)
{
    label1.Text = "GUI Init Error 2";
    Failure_Label.Text = ex1.Message;
}

并且“RunStateMachine”确实在与 UI 不同的线程上工作,允许显示表单,并且任何时候 RunStateMachine 需要与表单交互,例如更新消息,我调用一个函数,该函数使用 if(this.InvokeRequired ){this.Invoke(...);} else{...}

那么,我的问题是什么?
间歇性地,我的程序会挂起,这是因为计时器没有触发回调。我在上面的 try block 中添加了调试消息,还有许多其他地方告诉我它在哪里挂起,包括在“RunStateMachine”开头的消息。最终,我的程序卡在消息“Starting GUI Init Thread...”上

这告诉我线程计时器没有在我需要的时候运行一次
我的理论是它在计时器触发回调之前被垃圾收集。这意味着如果计时器是全局的,然后在我到达 RunStateMachine 时显式处理,它将完美运行......但我不想认为我解决了它只是为了发现从现在起一个月后间歇性出现。

想法?

最佳答案

My theory is that it's being garbage collected prior to the timer triggering the callback. That would mean if the timer was global, and then disposed explicitly when I get to RunStateMachine, that it will run perfectly... but I don't want to think I solved it just to find this coming up intermittently a month from now.

您似乎想要确认这是您的问题。 是的,这就是问题所在。

计时器存储在一个永远不会再被使用的局部变量中。这使它有资格进行 GC。定时器的 GC 导致终结,导致定时器被禁用。

我建议您将计时器存储在表单类的实例字段中,并在触发回调后将其从那里移除。

关于c# - System.Threading.Timer 没有启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12711954/

相关文章:

java - 主方法完成后的 Swing 计时器持久性

c# - 计时器之谜 - Forms.Timer 与 Threading.Timer

ios - Linphone linphone_core_iterate 崩溃

c++ - C++ 中的 ruby​​ `Object#freeze` 通讯器是什么?

java - 如何使线程不卡住整个 JFrame。 JAVA

c# - 清除 .NET 的 StringBuilder 内容的最佳方法

c# - 从每一帧视频中捕获单个像素行并将它们编译在一起

c# - 推送 bin/js 文件后,Servicestack 丢失 session ,直到缓存清除

ios - 运行干净后应用程序暂停但未收到错误

C# 字段命名指南?