C# >
System >
ComponentModel >
BackgroundWorker
The BackgroundWorker runs an operation on a separate and dedicated thread.
Time-consuming operations can cause the user interface (UI) to seem as frozen and stop responding while they are running.
BackgroundWorker class represents a solution to this.
Example
Use BackgroundWorker and progress bar to display a progress of import operation
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace BackgroundWorker
{
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
private BackgroundWorker worker = null;
public MainWindow()
{
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pBar.Value = e.ProgressPercentage;
lblStatus.Content = "Processing......" + pBar.Value.ToString() + "%";
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
// do your task here
for (int i = 0; i <= 100; i++)
{
Thread.Sleep(500);
if (worker == null)
break;
worker.ReportProgress(i);
}
}
private void worker_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
lblStatus.Content = "Task finished";
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (worker == null)
{
worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.ProgressChanged += worker_ProgressChanged;
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
}
if (worker.IsBusy != true)
{
// Start the asynchronous operation.
worker.RunWorkerAsync();
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
pBar.Maximum = 100;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
worker.CancelAsync();
worker = null;
}
}
}