如何正确进行穿线?

发布于 2024-11-18 22:07:27 字数 439 浏览 2 评论 0原文

我一直在研究 .Net 线程,并了解了 Threading.Task 和 Threading.Task.Parallel 类。现在,使用 Parallel 类的 ForEach 方法,我在单独的线程上处理每个对象。但是我相信 ForEach 方法会等待所有线程完成执行后再返回。这会导致那些先于其他线程完成的线程闲置。我想让这些线程持续工作。所以这就是我希望做的:

我有线程 A 负责从表中选择记录,然后启动 n 个工作线程来处理每个记录。

  1. 每次工作线程完成其工作时,它都应该向线程 A 询问下一条要处理的记录。

  2. 当向工作线程分配记录时,如果线程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.

  1. Every time a worker thread finishes its job, it should ask thread A for the next record to process.

  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟雨凡馨 2024-11-25 22:07:27

对于生产者消费者场景,您可以使用已经是线程安全的 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.

梦里梦着梦中梦 2024-11-25 22:07:27

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文