Background Worker in WPF

Sometimes we need to perform some time consuming tasks such as downloads etc. Execution of these tasks consumes a large amount of time. When we execute these types of tasks the user needs to have the responsiveness of the user interface maintained while the tasks proceed. The BackgroundWorker class is used to run time-consuming tasks in the background; it leaves the user interface responsive. Here we show an example of the BackgroundWorker class in WPF.

Step 1: First we create an instance of The BackgroundWorker class like this:

System.ComponentModel.BackgroundWorker MyWorker = new System.ComponentModel.BackgroundWorker();

Step 2: In order to run the BackgroundWorker process we use the RunWorkerAsync method of the BackgroundWorker class. This mehod is used to start the execution of the background process by the raising of the DoWork event. The DoWork EventHandler is run in a separate thread.

Here we take a Button (button1) and a Label Control (label1) to show the output:

private void button1_Click(object sender, RoutedEventArgs e)
{
    MyWorker.RunWorkerAsync();
}

public Window1()
{

    InitializeComponent();
    MyWorker.DoWork += MyWorker_DoWork;

}
private delegate void UpdateMyDelegatedelegate(int i);
private void UpdateMyDelegateLabel(int i)

{    label1.Content = "BckgroundWork:" + i.ToString();
 
}
private void MyWorker_DoWork(object Sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i <= 100; i++)
    {
        for (int j = 1; j <= 10000000; j++)
        {

        }
        if (MyWorker.CancellationPending)
        {
            e.Cancel = true;
            return;
        }
        UpdateMyDelegatedelegate UpdateMyDelegate = new UpdateMyDelegatedelegate(UpdateMyDelegateLabel);
                label1.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, UpdateMyDelegate, i+5);
 
    }
}

Here we use the Dispatcher; this is used when the background thread needs to interact with the UI thread. Here we set its priority to Normal.

Step 3: Now we take an another event RunWorkerCompleted; this event is used to raise an exception that shows that the Background Work has completed or been canceled.

Here we use a label (label2) to show the output:

public Window1()
{
 
    InitializeComponent();
    MyWorker.DoWork += MyWorker_DoWork;
    MyWorker.RunWorkerCompleted += MyWorker_RunWorkerCompleted;
}
private void MyWorker_RunWorkerCompleted(object Sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (!e.Cancelled)
    {
        label2.Content = "Complete My Background Work";

    }
    else
    {
        label2.Content = "Sorry it's Fail";
    }
}


The Output will be:

BckWPF1.jpg

Step 4: For determining if it worked or not, we use a Button Control and a TextBox Control and write the following code in the Button's Click Event like this:

private void button2_Click(object sender, RoutedEventArgs e)
{
    textBox1.Text = "Mahak";
 
}


The Output will be:

BckWPF2.jpg