title: C# Before closing application how to let background worker finish saving application state
body: <p>In a C# desktop application, a backgroundworker responsible for saving application state is being called in 2 situations. Once while the application is running. That works fine. Other when application is being closed, backgroundworker is called to save the application state but before it starts saving, the application is closed and nothing gets saved.</p>
  
  <p>I tried to solve it by using the AutoReset event class in DoWork and RunWorkerCompleted but didnt work because application closed before backgroundworker could save any thing.</p>
  
  <p>Question is - how can I make the main thread wait until backgroundworker finishes saving?</p>
  
  <pre><code>private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
  {
      this.saveAHToolStripMenuItem_Click(this, e);
  }
  
  private void saveAHAsToolStripMenuItem_Click(object sender, EventArgs e)
  {
      this.backgroundWorkerMain1.RunWorkerAsync(args);
  }
  
  private void backgroundWorkerMain1_DoWork(object sender, DoWorkEventArgs e)
  {
      saveMethod();
  }
  
  private void backgroundWorkerMain1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  {
      showResultOfSaving();
  }
  </code></pre>