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




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



Output


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