开发者

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

开发者 https://www.devze.com 2023-01-28 06:30 出处:网络
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

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 lin开发者_如何学运维e = 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消