I am trying to run a task in the background checking a database for a number of records in a 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'm getting a stack overflow after about two hours. The application is doing nothing during this time, just checking, and no jobs are being 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 are a ton of taskCheck()
in the call stack.
I'm guessing that taskCheck() never completes until taskCheck() completes, ergo overflow, and hence why they all remain in the stack.
This is obviously not the right way to go about this, so what is?