Friday, December 10, 2010

BackgroundWorker class

It helps in multithreading

here is an example

Suppose we've two Buttons Add and Display.
Add button performs a serious mathematical fns, which takes a lot of time.while the display button simply displays what we instructed.

using System.Threading;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int arg = (int)e.Argument;
e.Result = Add(arg);

}
private int Add(int ct)
{
int o, j;
o = 0;
j = 1;
int sum = 0;
for (int i = 0; i < ct; i++)
{
sum += o + j;
o = j;
j = sum;
Thread.Sleep(1000);
}
return sum;
}

private void btnAdd_Click(object sender, EventArgs e)
{
int arg = 4;
backgroundWorker1.RunWorkerAsync(arg);
}

private void btnshow_Click(object sender, EventArgs e)
{
MessageBox.Show("BlessyS.blogspot.com");
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show(e.Result.ToString());

}

0 comments:

Post a Comment