Articles → .NET → Asynchronously executing the task using BackgroundWorker

Asynchronously executing the task using BackgroundWorker









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




  1. Assign the value to the Result property in DoWork event.
  2. Get the value using Result property in RunWorkerCompleted event.


  1. In DoWork method, set the value of Result with current date and time.
  2. Pause for 3 seconds using sleep method.
  3. 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);
}




Picture showing the output of background worker in C#

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, January 8, 2011
 
Updated On  -  Saturday, November 2, 2019

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250