我试图在后台运行一个任务,在数据库中检查表中的许多记录,如果自上次检查以来该数目已更改,请获取这些记录并对其进行一些处理。
使用以下代码,大约两个小时后,我得到了堆栈溢出。在这段时间内,该应用程序什么也不做,只是在检查,没有任何作业被添加到数据库中。
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/