Reputation: 88
I would like to know what to use for tasks that need alot of performance.
Backgroundworker
, Thread
or ThreadPool
?
I've been working with Threads so far, but I need to improve speed of my applications.
Upvotes: 6
Views: 7359
Reputation: 941515
BackgroundWorker is the same thing as a thread pool thread. It adds the ability to run events on the UI thread. Very useful to show progress and to update the UI with the result. So its typical usage is to prevent the UI from freezing when works needs to be done. Performance is not the first goal, running code asynchronously is. This pattern is also ably extended in later .NET versions by the Task<> class and the async/await keywords.
Thread pool threads are useful to avoid consuming resources. A thread is an expensive operating system object and you can create a very limited number of them. A thread takes 5 operating system handles and a megabyte of virtual memory address space. No Dispose() method to release these handles early. The thread pool exists primarily to reuse threads and to ensure not too many of them are active. It is important that you use a thread pool thread only when the work it does is limited, ideally not taking more than half a second. And not blocking often. It is therefore best suited for short bursts of work, not anything where performance matters. Handling I/O completion is an ideal task for a TP thread.
Yes, it is possible to also use threads to improve the performance of a program. You'd do so by using Thread or a Task<> that uses TaskContinuationOptions.LongRunning. There are some hard requirements to actually get a performance improvement, they are pretty stiff:
Upvotes: 14
Reputation: 11186
This choice doesn't really matter. BackgroundWorker is a ThreadPool thread so that's no difference anyway. However, you could try to optimze the number of threads with ThreadPool.SetMaxThreads.
And you may want to use the System.Threading.Task class which could help to optimize parallel execution.
Upvotes: 0
Reputation: 75625
The framework for initiating CPU-intensive tasks in threads is irrelevant to your problem, unless you have overly-small-grained subtasks.
You need to split your work into subtasks that can be executed in parallel when you have more than one CPU to do so.
Upvotes: 1