0

I am looking for the ideal/thread safe implementation of a task queue that will start each task based on an internal condition (which i also only want to be checked at a timed interval), but also check that there aren't too many other tasks running. I also want a way to return progress of each task in the queue.

To give some background, I have a FileSystemWatcher that sends an event on a new folder being made. I then want to put this into a queue to process the folder, when it is no longer locked. But at the same time I want to guard against too many instances of the Process task from running.

Heres some pseudo-code of what I am after.

    private static void EventToQueue(object sender, EventArgs e)
    {
        ProcessQueue.Enqueue(Task, condition);
    }

    private static async void NewQueueObject(object sender, QueueObject e)
    {
        if (e.Condition && ProcessQueue.ActiveTask < 4)
        {
             var progress = new Progress<int>();

             progress.ProgressChanged += ( s, e ) =>
             {
                 UpdateProgress(e.Value);
             };
             await LongProcess(e, progress);
        }
        else
        {
            e.Delay(30);
        }
    }
  • Have you considered using Blocking Collection? – shay__ Mar 13 '16 at 07:59
  • Yea, I initially was going to try implement it with a BC. But I ended up a bit bogged down on how to do the consuming on an event based manner, based off those conditions without using a timer inside each of my T. – Mayura Vivekananda Mar 13 '16 at 09:06
  • Please look at the answer here - http://stackoverflow.com/questions/31427289/parallel-operations-with-audio-stream-c-sharp/31428762#31428762. It's also event based (`myWaveIn_DataAvailable`). – shay__ Mar 13 '16 at 10:07
  • Thanks. I have seen that implementation elsewhere, but I wasn't sure whether it was the correct/optimal way to do an event driven produce/consume. I am always a bit weary when i see while (true) loops. Would it be equally correct to only start the consumer on the produce event (since you know something will be coming once my condition is true), and run until there is nothing left to take? Or is that just a waste of time, since the thread the consumer is on is blocking, so won't effect performance. – Mayura Vivekananda Mar 13 '16 at 10:58
  • You could use `while (MyCondition())` instead of `while (true)` of course. As for the second question I don't think it's such a good practice to spawn a new consumer every time an event arrive. – shay__ Mar 13 '16 at 11:27

0 Answers0