Here are two examples that contrast using a BackgroundWorker to update the UI as the work is done and using it to update the UI only once the work is complete:
CSharp Code:
private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
BackgroundWorker worker = (BackgroundWorker)sender;
foreach (string filePath in System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)))
{
worker.ReportProgress(0, System.IO.Path.GetFileName(filePath));
}
}
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
string fileName = (string)e.UserState;
this.listBox1.Items.Add(fileName);
}
CSharp Code:
private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
BackgroundWorker worker = (BackgroundWorker)sender;
string[] fileNames = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
for (int index = 0; index < fileNames.GetUpperBound(0); index++)
{
fileNames[index] = System.IO.Path.GetFileName(fileNames[index]);
}
e.Result = fileNames;
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
string[] fileNames = (string[])e.Result;
this.listBox1.Items.AddRange(fileNames);
}
These examples show how you can pass data to the UI from a BackgroundWorker in two different ways without having to explicitly delegate, which is one of the first things everyone has trouble with when multi-threading.
Note that for the first example to work the WorkerReportsProgress property must be set to True.