只处理n项在同一时间同时使用任务并行库

编程入门 行业动态 更新时间:2024-10-12 22:26:55
本文介绍了只处理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项在同一时间同时使用任务并行库

本文发布于:2023-11-24 00:24:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623305.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   在同一

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!