控制台应用程序中的计时器
timer in console application
我正在使用 .NET compact framework 2.0 创建设备应用程序。我的应用程序中有一个 system.threading.timer
执行一些代码。它工作正常。我的问题是,当我通过双击 bin 文件夹中的 exe 来 运行 启动应用程序时,计时器启动并执行所有它能正常工作但它从不停止。即使在通过单击 X 按钮或从文件菜单关闭按钮关闭应用程序后,它 运行 仍在后台运行。我不明白我如何以及在何处停止或处理计时器,以便它在关闭应用程序后不会 运行。可能类似于 window 表单应用程序中的 form_closing 事件。我在 Google 中搜索了很多,但没有找到任何合适的答案。
该应用程序用于为设备生成数字输出
这是定时器事件的一些代码:
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.
时不工作
您可以在 Main()
中创建和处理它,并将它传递给任何需要它的方法吗?
private static void Main()
{
using (var timer = new System.Threading.Timer(TimerProc))
{
// Rest of code here...
}
}
更重要的是,这行代码:
Thread.CurrentThread.Join();
永远不会return,因为您要求当前线程等待当前线程终止。想一想……;)
所以您的解决方案可能只是删除该行代码。
所有关于 GC.Collect();
您的 stt 对象被使用一次,之后被指出将被删除并回收其内存。
如果您不相信请致电 stt.ToString();在 main 函数结束时,它会延长 stt live 直到 main 函数结束。
解决方案?
您可以将 stt 对象定义为静态对象 - 它保证它将一直存在到您的程序结束
推荐的解决方案是使用GC.KeepAlive(stt);您可以在 main 函数的末尾调用它,这将使 stt 远离破坏进程。
我正在使用 .NET compact framework 2.0 创建设备应用程序。我的应用程序中有一个 system.threading.timer
执行一些代码。它工作正常。我的问题是,当我通过双击 bin 文件夹中的 exe 来 运行 启动应用程序时,计时器启动并执行所有它能正常工作但它从不停止。即使在通过单击 X 按钮或从文件菜单关闭按钮关闭应用程序后,它 运行 仍在后台运行。我不明白我如何以及在何处停止或处理计时器,以便它在关闭应用程序后不会 运行。可能类似于 window 表单应用程序中的 form_closing 事件。我在 Google 中搜索了很多,但没有找到任何合适的答案。
该应用程序用于为设备生成数字输出 这是定时器事件的一些代码:
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.
时不工作您可以在 Main()
中创建和处理它,并将它传递给任何需要它的方法吗?
private static void Main()
{
using (var timer = new System.Threading.Timer(TimerProc))
{
// Rest of code here...
}
}
更重要的是,这行代码:
Thread.CurrentThread.Join();
永远不会return,因为您要求当前线程等待当前线程终止。想一想……;)
所以您的解决方案可能只是删除该行代码。
所有关于 GC.Collect();
您的 stt 对象被使用一次,之后被指出将被删除并回收其内存。
如果您不相信请致电 stt.ToString();在 main 函数结束时,它会延长 stt live 直到 main 函数结束。
解决方案?
您可以将 stt 对象定义为静态对象 - 它保证它将一直存在到您的程序结束
推荐的解决方案是使用GC.KeepAlive(stt);您可以在 main 函数的末尾调用它,这将使 stt 远离破坏进程。