我正在使用.NET紧凑框架2.0创建一个设备应用程序。我的应用程序中有一个system.threading.timer,它执行一些代码。效果很好。我的问题是,当我通过双击bin文件夹中的exe运行应用程序时,计时器会启动并执行它的所有工作,但它永远不会停止。它在后台运行,即使在关闭应用程序后,单击X按钮或从文件菜单关闭按钮。我不知道如何和在哪里停止或处置计时器,以便它不会运行后,关闭应用程序。可能类似于窗口窗体应用程序中的form_closing事件。我在谷歌上搜索了很多,但没有找到合适的答案。
该应用程序用于为设备生成数字输出,这里有一些计时器事件代码:
public static void Main()
{
// Some code related to the device like open device etc
// Then the timer
System.Threading.Timer stt =
new System.Threading.Timer(new TimerCallback(TimerProc), null, 1, 5000);
Thread.CurrentThread.Join();
}
static void TimerProc(Object stateInfo)
{
// It is my local method which will execute in time interval,
// uses to write value to the device
writeDigital(1, 0);
GC.Collect();
}当我在调试模式下运行代码时,它工作正常,当我停止程序时,计时器停止。但当我运行exe时不起作用。
发布于 2015-04-21 08:09:23
您可以在Main()中创建和处置它,并将其传递给任何需要它的方法?
private static void Main()
{
using (var timer = new System.Threading.Timer(TimerProc))
{
// Rest of code here...
}
}更重要的是,这一行代码:
Thread.CurrentThread.Join();将永远不会返回,因为您要求当前线程等待当前线程终止。考虑一下..。;)
所以,您的解决方案可能就是删除这一行代码。
https://stackoverflow.com/questions/29766170
复制相似问题