I have a queue of data that must be processed.
public static ConcurrentQueue<Data> queue = new ConcurrentQueue<Data>();
A bool variable that blocks thread generating if a current thread is running.
private static bool busy = false;
A timer that runs each 5000ms and runs a thread to process that queue sequentially.
timer = new System.Timers.Timer();
timer.Elapsed += Timer_Elapsed;
timer.Interval = 5000;
timer.Enabled = true;
private static void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{
if (!busy)
{
Thread thread= new Thread(Task);
thread.Start();
}
}
And the task function that must be run by every generated thread in background:
private static void Task()
{
Console.WriteLine("im busy");
busy= true;
Data data= null;
if (queue.Count > 0)
{
bool ok= queue.TryDequeue(out data);
if (ok && data!= null)
{
try{
LongTaskSync(data);
}catch(Exception){
Console.WriteLine("Error in longtasksync");
}
}
}
Console.WriteLine("im not busy");
busy= false;
}
The problem is that busy
variable sometimes get stuck to true
and never becomes false
. Don't know why. So queue gets full and no threads are generated to process the queue because the
if (!busy)
{
Thread thread= new Thread(Task);
thread.Start();
}
block is never reached.