如何添加任务优先级功能
我使用任务库作为图像压缩服务。我想压缩许多文件并发。但我希望该服务仅在用户空闲时运行(或者程序中不再有重要任务)。
我知道 threadPool 不支持“更改线程优先级”功能,因此任务也支持此功能。
我可以在更高级别的控制上开发该功能吗?(例如任务调度程序优先级)
i use Task Library for my image compression service. I would to compress many files concurrency. But i want the service run only when user is idle(or no more impotarnt task in programm).
I know that threadPool does not support "change thread priority" feature, so task also does support this feature.
Can i develop that functionality on higher level of control?(TaskScheduler priority for example)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如@zengr提到的,您可以使用优先级队列模式来解决这个问题。实际上MSDN 中有一个很好的示例,使用
ConcurrentQueue
每个优先级实例,然后包装该实例使用自定义IProducerConsumerCollection
实现它先从较高优先级队列中提取项目,然后再从较低优先级队列中提取项目。这种类型的实现使您的生产者能够确定应该有多少优先级,在添加项目时分配优先级,并让您的消费者首先处理具有最高优先级的项目,而无需了解优先级算法。As @zengr mentioned, you can use a priority queue pattern to solve this problem. There's actually a good sample in MSDN of implementing priority queues using
ConcurrentQueue<T>
instances per priority and then wrapping that with a customIProducerConsumerCollection<T>
implementation that pulls items from the higher priority queue before lower ones. This type of implementation enables your producer to determine how many priorities there should be, assign the priority when the item is added and lets your consumer work on the items with the highest priority first without having to ever understand the priority algorithm.您可以为任务并行库创建自定义
TaskScheduler
,然后通过将其实例传递给TaskFactory
构造函数来调度任务。以下是如何执行此操作的一个示例: 具有优先级的任务调度程序
You can create a custom
TaskScheduler
for the Task Parallel library and then schedule tasks on that by passing an instance of it to theTaskFactory
constructor.Here's one example of how to do that: Task Scheduler with priority