I want to perf开发者_如何学Corm 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
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
foreach (var item in sourceCollection)
{
Process(item);
}
with
Parallel.ForEach(sourceCollection, item => Process(item));
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.
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
精彩评论