由多个后台工作者处理的单个任务?
我有一个数组,它是文件夹中的文件列表,我正在处理这些文件并重命名它们。重新命名它们大约需要 15 分钟,每天都会这样做。我目前有 1 个后台工作者来处理这个问题并更新 UI。
我的问题是:如何使用超过 1 个后台工作程序来使用超过 25% 的 CPU 来执行此操作?
将数组分成 3 部分并调用 3 个独立的工作人员来完成他们的部分?
I have an array that is a list of files in a folder, I'm processing the files and renaming them. It takes about 15 minutes to rename them all, this is done daily. I currently have 1 Backgroundworker to handle this and update the UI.
My question is, this: How can I use more than 1 Backgroundworker to use more than 25% of the CPU to do this?
Split the array into 3 parts and call 3 separate workers to do their part?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用的是 .NET 4.0,那么您可以使用并行扩展,它将有效地为您完成此操作 - 您只需调用
Note,如果您的任务受到大量 IO 限制,那么使用多个线程可能会减慢速度而不是加快速度。
If you're using .NET 4.0 then you can use Parallel Extensions which will effectively do this for you - you'd just call
Note that if your task is heavily IO bound, using multiple threads may slow it down instead of speeding it up.
您可以创建一个在构造函数中接受文件夹路径的工作类。该工作类负责重命名其初始化文件夹上下文中的所有文件。该类可以有一个 DoWork() 方法,所有重命名工作都将在该方法中进行。这将允许您为每个文件夹创建 1 个工作程序类,然后在单独的线程上启动每个工作程序类,从而按照您的意愿分割工作。将线程优先级设置得更高将为您提供更多的 CPU 时间。
System.Threading 命名空间包含您需要的内容。
享受!
You could create a worker class that accepts a folder path in the constructor. This worker class is responsible for renaming all the files within the context of the folder it is initialized with. The class could have a DoWork() method where all your renaming work would occur. This will allow you to create 1 worker class per folder and then start each worker class on a separate thread thus splitting the work up however you would like. Setting the thread priority higher will give you more of time on the cpu.
System.Threading namespace contains what you need.
Enjoy!
如果处理每个项目的时间变化不大,那么拆分数组并给每个工作人员分配一部分可能就可以了。然而,您可能会发现集中保存列表并让每个工人说“给我一些工作要做”会更整洁,这应该确保工作分配得更均匀。它还能够适应更多变化的工人群体,只要系统资源允许,工人就可以来来去去。
If there is little variability in time to process each item then splitting the array and giving each worker a portion may be ok. However you may find it neater to keep the list centrally and have each worker say "give me some work to do", this should ensure that the work is shared out more evenly. It's also resilient to a more variable population of workers, workers could come and go as system resources permit.