Thursday, July 23, 2015

Few threading questions

Background Worker
Use Background Worker if you have a single task that runs in the background and needs to interact with the UI. The task of marshalling data and method calls to the UI thread are handled automatically through its event-based model. Avoid Background Worker if...
Your assembly does not have or does not interact directly with the UI,
You need the thread to be a foreground thread, or
You need to manipulate the thread priority.
Thread Pool
Use a Thread Pool thread when efficiency is desired. The Thread Pool helps avoid the overhead associated with creating, starting, and stopping threads. Avoid using the Thread Pool if...
the task runs for the lifetime of your application,
you need the thread to be a foreground thread,
you need to manipulate the thread priority, or
you need the thread to have a fixed identity (aborting, suspending, discovering).

Thread Class
Use the Thread class 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.
How to marshal back the exception to main thread?
1. Best bet is to replace the Thread with a Task (new in .NET 4.0). The Task class handles proper marshaling of the exception to whatever thread checks the result of the task.
2. You can use the exception as a parameter in event.
And handle it after sending the exception to other thread.
3. Dispatcher / SynchronisationContext is available
(ie. using WPF, Windows Forms, or a custom Dispatcher loop)
You can use ObserveOn + Catch to move the error back onto the Dispatcher thread. I've seen this used in a WPF application and it worked well.
4. No Dispatcher available
Instead of using Console.ReadKey(), use a ManualResetEvent and wait on it, then throw the mutable error afterwards:

No comments:

Post a Comment