Using BackgroundWorker in a WPF Application


Just sharing a small app that demonstrates the use of BackgroundWorker in WPF.

The app has two list boxes, one act as source of all the Process that needs to be processed and the other list box for the running and completed Processes.

The click of Start button starts the processing of Process.

Clicking on Cancel aborts the thread.

The XAML for the app.


<Window x:Class="BackgroundWorkerSampleApp.MainWindow"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Title="MainWindow" Height="324" Width="525" Loaded="Window_Loaded">
 <Grid Height="289">
 <ListBox Height="187" HorizontalAlignment="Left" Margin="20,52,0,0" Name="lstSource" VerticalAlignment="Top" Width="171"
 />
 <Button Content="Start" Height="41" HorizontalAlignment="Left" Margin="212,101,0,0" Name="btnStart" VerticalAlignment="Top" Width="75" Click="btnStart_Click" />
 <Button Content="Cancel" Height="42" HorizontalAlignment="Left" Margin="212,148,0,0" Name="btnCancel" VerticalAlignment="Top" Width="75" ContentStringFormat="Cancel" Click="btnCancel_Click" />
 <ListBox Height="187" HorizontalAlignment="Left" Margin="320,52,0,0" Name="lstDestination" VerticalAlignment="Top" Width="171" />
 <TextBlock Height="25" HorizontalAlignment="Left" Margin="195,252,0,0" Name="txtStatus" Text="" VerticalAlignment="Top" Width="232" />
 </Grid>
</Window>

The code behind for the app.


namespace BackgroundWorkerSampleApp
{
 using System.Collections.ObjectModel;
 using System.ComponentModel;
 using System.Threading;
 using System.Windows;

/// <summary>
 /// Interaction logic for MainWindow.xaml
 /// </summary>
 public partial class MainWindow : Window
 {
 #region Constants and Fields

private readonly BackgroundWorker backgroundWorker;

private readonly ObservableCollection<Process> obcProcess;

private readonly ObservableCollection<Process> obcRunningProcess;

private Thread workerThread;

#endregion

#region Constructors and Destructors

public MainWindow()
 {
 this.InitializeComponent();
 this.obcProcess = new ObservableCollection<Process>();
 this.obcRunningProcess = new ObservableCollection<Process>();
 this.lstSource.ItemsSource = this.obcProcess;
 this.lstDestination.ItemsSource = this.obcRunningProcess;
 this.lstSource.DisplayMemberPath = "ProcessName";
 this.lstDestination.DisplayMemberPath = "ProcessName";

// intialize BackgroundWorker class properties
 this.backgroundWorker = new BackgroundWorker();
 this.backgroundWorker.DoWork += this.backgroundWorker_DoWork;
 this.backgroundWorker.RunWorkerCompleted += this.backgroundWorker_RunWorkerCompleted;
 }

#endregion

#region Methods

/// <summary>
 /// Executes the process.
 /// </summary>
 /// <param name="backgroundWorker">The background worker.</param>
 private void ExecuteProcess(BackgroundWorker backgroundWorker)
 {
 if (this.obcProcess.Count > 0)
 {
 this.obcRunningProcess.Add(this.obcProcess[0]);
 backgroundWorker.RunWorkerAsync(this.obcProcess[0]);
 this.obcProcess.RemoveAt(0);
 }
 }

/// <summary>
 /// Handles the Loaded event of the Window control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
 var proc1 = new Process();
 proc1.ProcessName = "Process 1";

var proc2 = new Process();
 proc2.ProcessName = "Process 2";

var proc3 = new Process();
 proc3.ProcessName = "Process 3";

this.obcProcess.Add(proc1);
 this.obcProcess.Add(proc2);
 this.obcProcess.Add(proc3);
 }

/// <summary>
 /// Handles the DoWork event of the backgroundWorker control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
 private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
 {
 this.workerThread = Thread.CurrentThread;
 var process = e.Argument as Process;
 Thread.Sleep(5000);
 process.ProcessName = process.ProcessName + " Processed";
 }

/// <summary>
 /// Handles the RunWorkerCompleted event of the backgroundWorker control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
 private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
 if (e.Error != null)
 {
 MessageBox.Show(e.Error.Message);
 }
 else if (e.Cancelled)
 {
 MessageBox.Show("Cancelled");
 }
 else
 {
 if (this.obcProcess.Count > 0)
 {
 this.obcRunningProcess.Add(this.obcProcess[0]);
 this.backgroundWorker.RunWorkerAsync(this.obcProcess[0]);
 this.obcProcess.RemoveAt(0);
 }
 else
 {
 this.txtStatus.Text = "Processing Completed";
 }
 }
 }

/// <summary>
 /// Handles the Click event of the btnCancel control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
 private void btnCancel_Click(object sender, RoutedEventArgs e)
 {
 this.workerThread.Abort();
 this.txtStatus.Text = "Processing Aborted";
 }

/// <summary>
 /// Handles the Click event of the btnStart control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
 private void btnStart_Click(object sender, RoutedEventArgs e)
 {
 this.ExecuteProcess(this.backgroundWorker);
 }

#endregion
 }
}

Hope it helps.

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Please share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

CRM for You and Me

Customer Relationship Mgt App for the Professional

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Knowhere365

Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

Two Bite Tips

Valuable Tips To Grow Your Business

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM

EVOLVED365

Step into the world of a Dynamics 365 Consultant

Dianamics PCF Lady

Diana & Dynamics 365 & Power Platform

Sara Lagerquist

No Code Customization Concepts

innovativeaj

developer, designer, writer, fun loving, patriotic, humble and a sweet person inside out :) love and respect people who have a great sense of humor.

Temmy Wahyu Raharjo

Dreaming to be a clean coder and TDD minded programmer.

Transform 365

We blog about problems we face and code we write to help others

%d bloggers like this: