定时器在非常特殊的情况下无法触发
Timer failing to trigger in very specific circumstances
我正在尝试使用 System.Threading.Timer
在特定秒数后退出程序,但在特定情况下会失败。我已将其归结为最小测试用例。
using System;
using System.Collections.Generic;
using System.Threading;
class test {
static void SetTimer() {
new Timer(a => Environment.Exit(0), null, 1000L, 0L);
}
static void Main(string[] args) {
SetTimer();
for (;;) {
var v = new List<int>();
}
}
}
上面的程序应该会在一秒后退出,但它会无限期地挂起。
但是上面的代码每一部分都是必要的。计时器必须在单独的函数中设置;如果直接在Main中设置,程序会在一秒后退出。无限循环必须做一些不平凡的事情;如果它只是递增一个整数变量,程序会在一秒钟后退出。
这不是 C# 编译器本身的问题; F# 中的等效代码以相同的方式运行。
这是 Visual Studio 2022 在 Windows 10,csc -version
是 4.1.0-5.22109.6 (0c82c411)
。
这是 .Net 错误,还是我做错了什么?
问题是你的新定时器在执行回调之前已经消失了。您应该在保留对象的 class 中添加一个静态 Timer 计时器,以便它可以继续执行。这是我的答案:
using System;
using System.Collections.Generic;
using System.Threading;
class test
{
static Timer timer;
static void SetTimer()
{
timer = new Timer(a =>
{
Environment.Exit(0);
}, null, 1000L, 1000L);
}
static void Main(string[] args)
{
SetTimer();
for (; ; )
{
var v = new List<int>();
}
}
}
我正在尝试使用 System.Threading.Timer
在特定秒数后退出程序,但在特定情况下会失败。我已将其归结为最小测试用例。
using System;
using System.Collections.Generic;
using System.Threading;
class test {
static void SetTimer() {
new Timer(a => Environment.Exit(0), null, 1000L, 0L);
}
static void Main(string[] args) {
SetTimer();
for (;;) {
var v = new List<int>();
}
}
}
上面的程序应该会在一秒后退出,但它会无限期地挂起。
但是上面的代码每一部分都是必要的。计时器必须在单独的函数中设置;如果直接在Main中设置,程序会在一秒后退出。无限循环必须做一些不平凡的事情;如果它只是递增一个整数变量,程序会在一秒钟后退出。
这不是 C# 编译器本身的问题; F# 中的等效代码以相同的方式运行。
这是 Visual Studio 2022 在 Windows 10,csc -version
是 4.1.0-5.22109.6 (0c82c411)
。
这是 .Net 错误,还是我做错了什么?
问题是你的新定时器在执行回调之前已经消失了。您应该在保留对象的 class 中添加一个静态 Timer 计时器,以便它可以继续执行。这是我的答案:
using System;
using System.Collections.Generic;
using System.Threading;
class test
{
static Timer timer;
static void SetTimer()
{
timer = new Timer(a =>
{
Environment.Exit(0);
}, null, 1000L, 1000L);
}
static void Main(string[] args)
{
SetTimer();
for (; ; )
{
var v = new List<int>();
}
}
}