I am trying to create a single consumer and multiple producers pattern. The producers will add tasks to the BlockingCollection and Consumer will run the tasks. I want to know if there is a way to know if the execution of all the tasks spawned by consumer is complete.
public TaskQueue(IProducerConsumerCollection<Task> workTaskCollection)
{
_workTaskQueue = new BlockingCollection<Task>(workTaskCollection);
}
public void EnqueueTask(Action action, CancellationToken cancelToken = default(CancellationToken))
{
var task = new Task(action, cancelToken);
if (_workTaskQueue.TryAdd(task))
{
TaskHandler?.Invoke
(new TaskProcessingArguments
{
ISTaskAdded = true,
Message = "Task Added to Queue",
PendingTaskCount = _workTaskQueue.Count,
});
}
else
{
TaskHandler?.Invoke
(new TaskProcessingArguments
{
ISTaskAdded = false,
Message = "Timedout while adding Task to Queue",
PendingTaskCount = _workTaskQueue.Count,
});
}
}
public void DequeueTask()
{
foreach (var task in _workTaskQueue.GetConsumingEnumerable())
try
{
if (!(task.IsCanceled) && task.Status == TaskStatus.Created)
{
task.Start();
}
}
catch (Exception ex)
{
}
}
public static void Run()
{
Task.Factory.StartNew(() =>
{
taskQueue.DequeueTask();
}, TaskCreationOptions.LongRunning);
}