Using the BackgroundWorker component
The asynchronous operation we used in the previous examples used the thread pool explicitly to do the long running work on another thread. Updating the UI required marshaling code to the UI thread from another thread, to keep the rule of updating the UI from the UI thread intact. All this required some manually managed code.
An alternative is using the BackgroundWorker
class that provides automatic management and marshaling for the purpose of performing a long running operation on a background thread.
In this recipe, we'll use the BackgroundWorker
to do asynchronous operations without blocking the UI thread and understand its pros and cons.
Getting ready
We'll duplicate most of the UI from the CH11.AsyncCalc
project, so keep it open while we create the new project.
How to do it...
We'll count prime numbers (as before) on a different thread, but we'll let the BackgroundWorker
take care of all the gory details.
Create a new WPF Application named
CH11.AsyncCalcWithBackgroundWorker...