2011-11-29

Thread Type Selection

Below are criteria to use when selecting a threading type, from a user claws in a stack overflow discussion It looks as threads in three different categories depending on the target use, asynchronous delegates, BackgroundWorker, or as ThreadPool:
  1. Asynchronous Delegates - Used when you have work items that should be handled in the background and you care when they finish.
  2. BackgroundWorker
    • Use BackgroundWorker if you have a single task that runs in the background and needs to interact with the UI. and use it if you don't care when they finish their task. The task of marshalling data and method calls to the UI thread are handled automatically through its event-based model.
    • Avoid BackgroundWorker if (1) your assembly does not already reference the System.Windows.Form assembly, (2) you need the thread to be a foreground thread, or (3) you need to manipulate the thread priority.
  3. ThreadPool
    • Use a ThreadPool thread when efficiency is desired. The ThreadPool helps avoid the overhead associated with creating, starting, and stopping threads.
    • Avoid using the ThreadPool if (1) the task runs for the lifetime of your application, (2) you need the thread to be a foreground thread, (3) you need to manipulate the thread priority, or (4) you need the thread to have a fixed identity (aborting, suspending, discovering).
  4. Thread class - Use this for long-running tasks and when you require features offered by a formal threading model, e.g., choosing between foreground and background threads, tweaking the thread priority, fine-grained control over thread execution, etc.