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++)
{



shoeb ahmadPosted Sep 3, 2014, 2:48 AM
nice work thanks