The BackgroundWorker class allows you to run an operation on a separate, dedicated thread.
Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running( i.e it seems like white faded screen ). In such a case this background worker will helpful so the fading are avoided bcoz it was running under seperate dedicated thread.
Three events available in backgroundworker.
1.DoWork: In which we need write the business logic
2.Runworkercompleted: This event automatically fired when the bgworker completes its process
3.Progresschanged: from which we can get the percentage of completed process.
To start the bgworker use the method RunWorkerAsync()
Consider the code snippet below create a win form and select 2 button as named BgworkerButton,NormalButton add a background worker as backgroundWorker1 and test it.
string str = string.Empty;
public Form1()
{
InitializeComponent();
}
private void BgworkerButton_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 10000; i++)
str = str + " bg" + i.ToString();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Completed");
}
private void NormalButton_Click(object sender, EventArgs e)
{
for (int i = 1; i <= 10000; i++)
str = str + " " + i.ToString();
MessageBox.Show("Completed");
}
BackgroundWorker Control
Posted by
Nirmal
Friday, November 7, 2008
0 comments:
Post a Comment