【问题标题】:c#.net looping thread stack overflowc#.net循环线程堆栈溢出
【发布时间】:2009-05-05 21:43:56
【问题描述】:

我正在尝试在后台运行一项任务,检查数据库中表中的许多记录,如果自上次检查后数量发生变化,请获取这些记录并对其进行一些处理。

使用以下代码,我在大约两个小时后遇到堆栈溢出。应用程序在这段时间内什么都不做,只是检查,没有作业被添加到数据库中。

private Thread threadTask = null;
private int recordCount = 0;

private void threadTask_Start()
{
    if (threadTask == null) {
        threadTask = new Thread(taskCheck);
        threadTask.Start();
    }
}

private void taskCheck()
{
     int recordCountNew = GetDBRecordCound();
     if (recordCountNew != recordCount)
     {
         taskDo();
         recordCount = recordCountNew; // Reset the local count for the next loop
     }
     else
         Thread.Sleep(1000); // Give the thread a quick break

     taskCheck();          
}

private void taskDo()
{
    // get the top DB record and handle it
    // delete this record from the db
}

当它溢出时,调用堆栈中有大量的taskCheck()。 我猜在 taskCheck() 完成之前 taskCheck() 永远不会完成,因此溢出,因此它们都保留在堆栈中。 这显然不是解决这个问题的正确方法,那是什么?

【问题讨论】:

  • 你不是在taskCheck()的底部调用taskCheck()吗?下划线是错字吧?
  • 我想我明白你来自哪里。否 - C#/.NET 不适用 TCO - 您必须手动执行循环。

标签: c# .net winforms multithreading


【解决方案1】:

你得到一个堆栈溢出,因为在 taskCheck 结束时,你再次调用 taskCheck。你永远不会退出函数 taskCheck,你只会越来越多地调用,直到堆栈溢出。你应该做的是在 taskCheck 中有一个 while 循环:

private void taskCheck()
{
   while(true)
   {
       int recordCountNew = GetDBRecordCound();
       if (recordCountNew != recordCount)
       {
           taskDo();
           recordCount = recordCountNew; // Reset the local count for the next loop
       }
       else
           Thread.Sleep(1000); // Give the thread a quick break
   }
}

【讨论】:

  • 他还应该有一个 try{}catch(ThreadAbortException){}finally{} 块。
  • 好点。如果抛出异常(数据库调用?),执行流程将退出 while 循环,while 循环将停止执行。如果发生这种情况,我通常会在消息日志或弹出窗口中通知用户。替代品?
  • 正在进行其他数据库处理,如果出现问题,我将使用它来控制“true”值。
【解决方案2】:

我假设你在哪里有 task_Check(),你实际上是指 taskCheck()(反之亦然)。也就是说,您正在调用 taskCheck() 方法recursively。避免在此处讨论架构,您可以删除该调用并让 threadTask_Start() 在 while 循环中重复一次该过程。

【讨论】:

    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2014-12-15
    相关资源
    最近更新 更多