只处理n项在同一时间同时使用任务并行库 [英] Processing only n items at a time concurrently using Task Parallel Library

查看:133
本文介绍了只处理n项在同一时间同时使用任务并行库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一切都发生在一个窗口服务。

This is all happening in a windows service.

我有一个问答LT; T> (实际上是 ConcurrentQueue< T> )控股的项目等待处理。但是,我并不想在同一时间只有一个进程,我想,其中n是一个可配置的整数同时,处理n项。

I have a Queue<T> (actually a ConcurrentQueue<T>) holding items waiting to be processed. But, I don't want to process only one at a time, I want to process n items concurrently, where n is a configurable integer.

我如何去这样做使用任务并行库?

How do I go about doing this using the Task Parallel Library?

我知道,太平人寿将分区集合代表开发人员并行处理,但不知道这是说我以后该功能。我是新来的多线程和TPL。

I know that TPL will partition collections on behalf of the developer for concurrent processing, but not sure if that's the feature that I'm after. I'm new to multithreading and TPL.

推荐答案

使用 BlockingCollection&LT; T&GT; 而不是 ConcurrentQueue&LT; T&GT; ,然后就可以开始任意数量的消费者线程,并使用 BlockingCollection 中以方法。如果集合是空的,方法将在调用者线程等待项目添加自动阻止,否则线程将消耗所有并联队列中的项目。然而,由于你的问题中提到了使用第三方物流的事实证明, Parallel.ForEach 必须在与 BlockingCollection 使用的一些问题检查职位的更多细节。所以你必须要管理你的创造消费者线程你的自我。 新线程(/ *消费方式* /)新任务() ...

Use BlockingCollection<T> instead of ConcurrentQueue<T>, then you can start any number of consumer threads and use Take method of the BlockingCollection. if the collection is empty, the Take method will automatically block in the caller thread waiting for items to be added, otherwise the threads will consume all the queue items in parallel. However as your question mentioned out the use of TPL it turns out that Parallel.ForEach have some issues when using with BlockingCollection check this post for more details. so you have to manage creation of your consumer threads your self. new Thread(/*consumer method*/) or new Task()...

这篇关于只处理n项在同一时间同时使用任务并行库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆