创建多个后台工作线程的最佳方法是什么?
我想同时执行多项任务(远程共享上的磁盘 IO)。我不想阻止用户界面。我想我需要创建一个执行以下操作的自定义类...
- 接受请求并将其排队(使用堆栈)
- 检查线程池,如果线程可用,则使用请求的信息启动它
- 当每个线程完成时检查堆栈待处理的请求...
有更好的方法吗?
是否有可用于此目的的课程?
我应该使用BackgroundWorker类的池还是其他东西?
我是否必须在自定义类中实现BackgroundWorker 类才能创建多个线程?
我想创建最多 8 个线程来删除文件和文件夹。我需要查询堆栈上的项目数以更新 UI。
我目前的代码使用单个 BackgroundWorker 线程来删除文件和文件夹(这可以防止 UI 锁定,但需要很长时间,我倾向于同时运行多个实用程序)。
谢谢, 李
I want to perform several tasks (Disk IO on Remote Shares) at the same time. I do not want to block the UI. I think I need to create a custom class that does the following...
- Accepts and queues a request (using a Stack)
- Checks the thread pool and if a thread is available starts it with the requested info
- As each thread completes check the stack for pending requests...
Is there a better way to do this?
Is there a class already available for this?
Should I use a pool of the BackgroundWorker class or something else?
Will I have to implement the BackgroundWorker class in a custom class so that I can create multiple threads?
I want to create up to 8 threads for deleting files and folders. I need to query the number of items on the stack for updating the UI.
I currently have the code working with a single BackgroundWorker thread to delete the files and folders (which keeps the UI from locking, but it takes so long I tend to run several of the utilities at the same time).
Thanks,
Lee
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是 .NET 4,那么任务并行库看起来正是您所需要的。 MSDN 上的参考在这里: http://msdn.microsoft.com/en-us /library/dd460717.aspx 。
具体来说,示例位于 http://msdn.microsoft.com/en-us/ library/dd537608.aspx 建议替换
为
只是要小心代码中的死锁;特别是,要进行广泛的测试,因为有时在 Windows 网络堆栈的深处可能会发生奇怪的事情。
If you're using .NET 4, then the Task Parallel Library looks like exactly what you need. Reference on MSDN is here: http://msdn.microsoft.com/en-us/library/dd460717.aspx .
Specifically, the example at http://msdn.microsoft.com/en-us/library/dd537608.aspx suggests replacing
with
Just be wary of deadlocks in your code; in paricular, test extensively, as there can be strange things that happen sometimes in the depths of the Windows networking stack.
您可以使用BackgroundWorker池,但请注意它是专为在简单的多线程场景中使用而设计的。
我建议您使用 TPL 或 Threadpool 来解决您的此类问题,但如果您的代码已经在使用一个 BackgroundWorker,那么您会更快,将其重写为 8 而不是使用 TPL。
也许这个讨论会帮助您做出决定:BackgroundWorker 与BackgroundThread
You can use a pool of BackgroundWorker, but note it is designed for use in simple multi-threaded scenarios.
I would recommend using TPL or Threadpool for your kind of problem, but if your code is already working with one BackgroundWorker you will be much faster, rewriting it for 8 instead of using TPL.
Maybe this discussion will help your decision: BackgroundWorker vs. BackgroundThread