C# - BlockingCollection:我们可以让 2 个线程 Take() 相同的值吗?
我一直在使用 Tasks 和 BlockingCollections,它们做得很好。但据我了解, Take() 方法会删除队列中的对象。但是如果您希望 2 个任务同时访问相同的值怎么办?
假设我正在读取一个文件,并通过blockingCollection.Add() 将每一行发送到2 个任务,但我希望这两个任务以相同的顺序获取相同的行。 (每个任务都会对同一行执行不同的操作)
我该如何去做呢? BlockingCollection 可以做到这一点吗?或者我使用事件来传递值?如果是这样,请解释如何在另一个任务/线程中触发一个任务/线程的事件。
[编辑] 如果我这样做怎么办:
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
}
不是很优雅......它也不能保证同步。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您只想为每个线程一个单独的队列。以相同的顺序将相同的对象添加到每个队列,然后每个线程可以随意删除它们。
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.