I'm trying to use a System.Threading.Timer
to exit a program after a certain number of seconds, and it's failing in specific circumstances. I've boiled it down to a minimum test case.
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>();
}
}
}
The above program should exit after one second, but it just hangs indefinitely.
But every part of the above code is necessary. The timer has to be set in a separate function; if it is set directly in Main, the program exits after one second. The infinite loop has to be doing something nontrivial; if it just increments an integer variable, the program exits after one second.
It's not the C# compiler per se at fault; the equivalent code in F# behaves the same way.
This is with Visual Studio 2022 on Windows 10, and csc -version
is 4.1.0-5.22109.6 (0c82c411)
.
Is this a .Net bug, or am I doing something wrong?
CodePudding user response:
The problem is that your new Timer is already gone before the callback is executed. You should add a static Timer timer in the class that retains the object so it can keep executing. Here's my answer:
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>();
}
}
}