I’m trying to code part of my application that runs a BackgroundWorker process that performs a time-consuming operation. In the main thread, a timer updates a progress bar (this is a continuation of this question). However, this code display no MessageBoxes. Setting a breakpoint on the foreach (String word in this.words) line in the SearchButton_Click event handler reveals that this.words has no values, i.e. this.words.Count() == 0.
public partial class Form1 : Form
{
System.Windows.Forms.Timer searchProgressTimer;
List<String> words;
public Form1()
{
InitializeComponent();
words = new List<String>(3);
}
private void SearchDatabase_Click(object sender, EventArgs e)
{
this.searchProgressTimer.Start();
SearchBackgroundWorker.RunWorkerAsync();
foreach (String word in this.words) // BREAKPOINT HERE
MessageBox.Show(word);
}
private void SearchBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Time-consuming operation
String filename = @"http://www.bankofengland.co.uk/publications/Documents/quarterlybulletin/qb0704.pdf";
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(filename), @"file.pdf");
List<String> word_result = new List<String> { "word1", "word2", "word3" };
e.Result = word_result; // e.result is an Object, and word_result is a List.
}
private void SearchBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.searchProgressTimer.Stop();
this.searchProgressBar.Value = 0;
this.words = (List<String>)e.Result;
}
}
My guess as to why this occurs is because the BackgroundWorker thread isn’t finished with its operation before the main UI thread moves on to the foreach loop. I think I understand that part. However, since I want to perform the time-consuming operation in a background thread so the progress bar can update its value as said operation runs, then use the result of the BackgroundWorker immediately after its finished, how would I do this?
Please edit my title if it doesn’t get the point across as well. I wasn’t sure how to phrase this.
Do whatever you want to do in that RunWorkerCompleted event:
Since you are getting this information from the background worker, the only way you know you have your list is when the worker completes.