C # .net stack stream overflow
I am trying to run a task in the background, checking the database for the number of records in the table, and if the number has changed since the last check, get those records and do some work on them.
Using the following code, I get a stack overflow after about two hours. During this time, the application does nothing, it just checks, and no jobs are added to the database.
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
}
When it overflows, there is a ton in the call stack taskCheck()
. My guess is that taskCheck () never completes until taskCheck () completes, ergo overflows and hence why they all stay on the stack. This is obviously not the most correct way to do it, so what?
a source to share
You get a stack overflow because at the end of taskCheck you call taskCheck again. You never exit the taskCheck function, you just call more and more until your stack overflows. What you should do is include a while loop in taskCheck:
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
}
}
a source to share
I assume you have task_Check (), you actually mean taskCheck () (or vice versa). That is, you are calling the taskCheck () method recursively . Avoiding the discussion of architecture here, you can remove that call and ask threadTask_Start () to repeat the process once in a while loop.
a source to share