【发布时间】: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