System.Threading.Timer不会触发

Mil*_*vic 1 c# timer

我是新来的...

我有一个问题,如果有人可以帮助我.

它是关于计时器(System.Threading.Timer).

我想打破不可避免的递归:我在datarow中有两列,它们是相互依赖的(price_without_VAT和price_with_VAT).设置其中一个肯定会导致StackOverflowException.所以这就是这个想法:

bool flag = true;
void Reset(object state) { flag = true; }
Run Code Online (Sandbox Code Playgroud)

现在,包装用于更改其中一列的值的方法:

{
    if(flag)
    {
        flag = false;
        System.Threading.Timer tmr = new System.Threading.Timer(new System.Threading.TimerCallback(Reset), null, 10, System.Threading.Timeout.Infinite);
        datarow.other_column = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

datarow.other_column.value行将立即触发上述方法,但不会有递归,因为flag为false.在10毫秒标志应该回到真,一切都恢复正常.

现在,当我按照DEBUGGER中的代码进行操作时,一切正常,但是当我启动应用程序NORMALLY重置功能根本不会触发,标志永远停留在虚假状态,并且一切都是假的.我玩弄due_time参数但似乎没有任何帮助.

有任何想法吗?

Jim*_*hel 6

虽然我同意那些说你应该找到另一种方法来阻止无限递归的人,但你的计时器不会触发的原因可能是因为它被优化了.我最近遇到了其他事情.

假设您想要一个定期计时器:

void SomeMethod()
{
    Timer MyTimer = new Timer(MyTimerProc, null, 3000, 3000);
    // other stuff goes here
}
Run Code Online (Sandbox Code Playgroud)

现在,您在调试模式下运行它,一切正常.但是当你在发布模式下运行它时,计时器永远不会触发.这是因为它被优化了.你需要做的是保持它(使用GC.KeepAlive)或者using:

using (Timer MyTimer = new Timer(MyTimerProc, null, 3000, 3000))
{
    // other stuff here
}
Run Code Online (Sandbox Code Playgroud)