Spectraljump
Spectraljump

Reputation: 4637

C# - BlockingCollection: Can we have 2 threads Take() the same value?

I've been using Tasks and BlockingCollections and they do a great job. But as I understand, the Take() method removes the object in the queue. But what if you want 2 tasks to access the same value at the same time?

Let's say that I'm reading a file and I send each line via blockingCollection.Add() to 2 Tasks but I want both tasks to get the same lines and in the same order. (each task will do something different to the same line(s))

How do I go about doing that? Can BlockingCollection do this? Or do I use events to pass values? If so, please explain how you'd make a task/thread's event fire in another task/thread.

[EDIT] What if I do this:

while (!lineCollection.IsCompleted)
{
      Line line = lineCollection.Take();
      //do my processing
      //then I add the original line back to the collection
      lineCollection.Add(line);
      //and use a "wait one" to wait for T2 to Take this line aswell 
      //Then continue my while loop
}

not very elegant... It also wouldn't guarantee synchronization.

Upvotes: 1

Views: 856

Answers (1)

Gabe
Gabe

Reputation: 86718

It sounds like you just want a separate queue for each thread. Add the same objects to each queue in the same order and then each thread can remove them at their leisure.

Upvotes: 3

Related Questions