如何正确进行穿线?
我一直在研究 .Net 线程,并了解了 Threading.Task 和 Threading.Task.Parallel 类。现在,使用 Parallel 类的 ForEach 方法,我在单独的线程上处理每个对象。但是我相信 ForEach
方法会等待所有线程完成执行后再返回。这会导致那些先于其他线程完成的线程闲置。我想让这些线程持续工作。所以这就是我希望做的:
我有线程 A 负责从表中选择记录,然后启动 n 个工作线程来处理每个记录。
每次工作线程完成其工作时,它都应该向线程
A
询问下一条要处理的记录。当向工作线程分配记录时,如果线程
A
耗尽,它应该返回数据库并获取更多记录。我猜这个分配过程必须包装在关键部分块中。
谁能给我指出适合我的场景的教程?
I've been studying .Net threading and have learned about the Threading.Task
and Threading.Task.Parallel
classes. Right now using the ForEach
method of Parallel
class I process each object on a separate thread. However I beleive the ForEach
method waits for all threads to finish executing before it comes back. This results in those threads that finish before others to sit idle. I want to have these threads working constantly. So this is what I'm hoping to do:
I have thread A
in charge of slice selecting records from the table and then starting n worker threads to process each record.
Every time a worker thread finishes its job, it should ask thread
A
for the next record to process.When allocating records to worker threads, if thread
A
runs out, it should go back to the database and fetch some more. I'm guessing this allocating process has to be wrapped within a critical section block.
Can anyone point me to a tutorial that fits my scenario?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于生产者消费者场景,您可以使用已经是线程安全的 ConcurrentQueue 。
这意味着您可以从任何 A 线程填充它,并从所有其他使用者线程弹出要处理的项目,而无需使用锁定。
For a producer consumer scenario you can use the ConcurrentQueue which is already thread safe.
That means that you can fill it from any A thread, and pop out items to work on from all other consumer threads without using locking.
您所讨论的通常称为“线程池”。 MSDN 的“如何:使用线程池”< /a> 可能与您的兴趣相关。
What you're discussing is typically called a "thread pool". MSDN's "How to: Use a Thread Pool" will probably be relevant to your interests.