user1660943
user1660943

Reputation: 45

Creating worker "tasks" to dealing with limited resources

I am looking for a mechanism already in c# that will allow me to do something like this:

Any recommendations on using c# accomplish something like this?

Upvotes: 0

Views: 121

Answers (2)

Servy
Servy

Reputation: 203812

The BlockingCollection<T> class makes producer/consumer queues very easy to work with.

var queue = new BlockingCollection<Action>();

//put work to do in the queue
for (int i = 0; i < 10; i++)
    queue.Add(() => ProcessImage());
queue.CompleteAdding();

//create two workers
for (int i = 0; i < 2; i++)
{
    Task.Factory.StartNew(() =>
    {
        foreach (var action in queue.GetConsumingEnumerable())
            action();
    });
}

//to cancel the work, empty the queue
Task.Delay(5000)
    .ContinueWith(t =>
    {
        queue.GetConsumingEnumerable().Count();
    });

Upvotes: 1

TalentTuner
TalentTuner

Reputation: 17556

use Seamphore + ConcurrentQueue combo

Upvotes: 0

Related Questions