title: How do I return a list from a BackgroundWorker for use in the next line of code in the UI thread?
body: <p>I'm trying to code part of my application that runs a <code>BackgroundWorker</code> process that performs a time-consuming operation. In the main thread, a timer updates a progress bar (this is a continuation of <a href="https://stackoverflow.com/questions/11476364/how-do-i-set-a-progressbar-to-increment-at-each-tick-of-a-timer/11476468#11476468">this question</a>). However, this code display no <code>MessageBoxes</code>. Setting a breakpoint on the <code>foreach (String word in this.words)</code> line in the <code>SearchButton_Click</code> event handler reveals that <code>this.words</code> has no values, i.e. <code>this.words.Count() == 0</code>.</p>
  
  <pre><code>public partial class Form1 : Form
  {
      System.Windows.Forms.Timer searchProgressTimer;
      List&lt;String&gt; words;
  
      public Form1()
      {
          InitializeComponent();
  
          words = new List&lt;String&gt;(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&lt;String&gt; word_result = new List&lt;String&gt; { "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&lt;String&gt;)e.Result;
      }   
  }
  </code></pre>
  
  <p>My guess as to why this occurs is because the <code>BackgroundWorker</code> thread isn't finished with its operation before the main UI thread moves on to the <code>foreach</code> 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 <code>BackgroundWorker</code> immediately after its finished, how would I do this?</p>
  
  <p>Please edit my title if it doesn't get the point across as well. I wasn't sure how to phrase this. </p>