I am using ConcurrentQueue to store messages from multiple threads.
How to create some background thread which will automatically get triggered when my queue has something in it?
I am using ConcurrentQueue to store messages from multiple threads.
How to create some background thread which will automatically get triggered when my queue has something in it?
You might start a worker thread with a Thread.Sleep() in it and after sleep ask if your queue has count > 0.
You might put the thread initializing code in the constructor of your class or an initializer method.
...
var queue = new ConcurrentQueue<T>(); //Use your generic type for T
var thread = new Thread(() => WorkOnQueue(queue));
thread.IsBackground = true;
thread.Name = "My Worker Thread";
thread.Start();
...
private void WorkOnQueue(ConcurrentQueue queue)
{
var pause = TimeSpan.FromSeconds(0.05);
while (!abort) // some criteria to abort or even true works here
{
if (queue.Count == 0)
{
// no pending actions available. pause
Thread.Sleep(pause);
continue;
}
DoWork(); //Contains the TryDequeue ...
}
}