Saturday, July 25, 2009

BackgroundWorker Component

BackgroundWorker Component can be used in situations where long running operations is likely to affect the responsiveness of the UI.

Here I am writing a method within an intention to simulate a delay using Thread Sleep. If I am directly calling the method from button click, the UI will freeze till the operation is complete.
Instead I am using DoWork event of BackgroundWorker Component in conjunction with RunWorkerAsync method.




















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 sum = Add(4);
//MessageBox.Show(sum.ToString());
int arg = 4;
backgroundWorker1.RunWorkerAsync(arg);
}

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

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

No comments:

Post a Comment