c# - C#.net循环线程堆栈溢出

标签 c# .net winforms multithreading

我试图在后台运行一个任务,在数据库中检查表中的许多记录,如果自上次检查以来该数目已更改,请获取这些记录并对其进行一些处理。

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

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。您永远不会退出函数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
   }
}

关于c# - C#.net循环线程堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/827037/

相关文章:

c# - 为什么 C# 为相同的源代码生成不同的 EXE?

c# - 如何在不同线程中使用 Entity Framework ?

c# - 在 C# 5 中表示异步序列

.net - 为什么我会得到 "The type of namespace name ' bla' does not exist...” 没有更改后?

.net - 这种情况下需要STA消息循环吗?

c# - 使用 ASP.Net Core 3.0 中的表单添加到模型的 IList

.net - 在 .NET 事件中使用 ref 参数时 PowerShell 崩溃

c# - 是否可以在不更改文本长度的情况下动态调整 c# 中的标签大小?

winforms - 当窗口关闭时,我的应用程序失去焦点

c# - CancellationTokenSource 需要建议