Articles → CSHARP → Asynchronously Executing The Task Using Backgroundworker
Asynchronously Executing The Task Using Backgroundworker
Scenario
private void CreateFile(string filename) {
FileInfo f = new FileInfo("d:\\File\\" + filename + ".txt");
StreamWriter w = f.CreateText();
w.WriteLine("This is the text");
w.Close();
}
private BackgroundWorker _BackgroundWorker;
if (_BackgroundWorker == null) {
_BackgroundWorker = new BackgroundWorker();
_BackgroundWorker.DoWork += new DoWorkEventHandler(_BackgroundWorker_DoWork);
}
_BackgroundWorker.RunWorkerAsync();
void _BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) {
for (int i = 1; i < 10000; i++) {
CreateFile(i.ToString());
}
}
Passing Parameter Between Dowork And Runworkercompleted
Example
- In the DoWork method, set the value of Result with the current date and time
- Pause for 3 seconds using the sleep method
- Display the current DateTime and DoWork datetime
private void Form1_Load(object sender, EventArgs e) {
BackgroundWorker _BackgroundWorker = new BackgroundWorker();
_BackgroundWorker.DoWork += _BackgroundWorker_DoWork;
_BackgroundWorker.RunWorkerCompleted += _BackgroundWorker_RunWorkerCompleted;
_BackgroundWorker.RunWorkerAsync();
}
void _BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
string timeString = string.Format("Current time: {0}{1} DoWork time:{2}", DateTime.Now.ToString(), Environment.NewLine, e.Result.ToString());
MessageBox.Show(timeString);
}
void _BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) {
e.Result = DateTime.Now;
System.Threading.Thread.Sleep(3000);
}
Output
Click to Enlarge