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


















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);
}





Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, January 08, 2011
 
Updated On  -  Saturday, November 02, 2019

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250