How to use WPF Background Worker

backgroundworker, c#, multithreading, wpf

Solution

Add using

using System.ComponentModel;

Declare Background Worker:

private readonly BackgroundWorker worker = new BackgroundWorker();

Subscribe to events:

worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;

Implement two methods:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender, 
                                           RunWorkerCompletedEventArgs e)
{
    //update ui once worker complete his work
}

Run worker async whenever your need.

worker.RunWorkerAsync();

Track progress (optional, but often useful)

a) subscribe to `ProgressChanged` event and use `ReportProgress(Int32)` in `DoWork`

b) set `worker.WorkerReportsProgress = true;` (credits to @zagy)

Problem

In my application I need to perform a series of initialization steps, these take 7-8 seconds to complete during which my UI becomes unresponsive. To resolve this I perform the initialization in a separate thread: ``` public void Initialization() { Thread initThread = new Thread(new ThreadStart(InitializationThread)); initThread.Start(); } public void InitializationThread() { outputMessage("Initializing..."); //DO INITIALIZATION outputMessage("Initialization Complete"); } ``` I have read a few articles about the `BackgroundWorker` and how it should allow me to keep my application responsive without ever having to write a thread to perform lengthy tasks but I haven't had any success trying to implement it, could anyone tell how I would do this using the `BackgroundWorker`?

Original source