title: Waiting for a long process and still updating UI
body: <p>I've been attempting to create a task that writes to a database without blocking the UI thread. The biggest problem I'm having is waiting for that process to finish without the blocking happening.</p>
  
  <p>I've been trying to avoid using <code>DoEvents</code> (though it's used quite frequently through this program right now, I'd like to move out of using it while moving forward).</p>
  
  <p>I've attempted to create the process to run on a 2nd thread and waiting for it to finish as well as using a <code>BackgroundWorker</code>.</p>
  
  <p>The problem I have with this is not having the code run in a different thread, but trying to find a way to wait for it to finish.</p>
  
  <p>Basically, Right now I do the following:</p>
  
  <ol>
  <li>Connect to the database</li>
  <li>Create a background worker (or thread) to do the writing to the database (I will probably end up with the <code>BackgroundWorker</code> so I can use the <code>ReportProgress</code></li>
  <li>Start the thread or <code>BackgroundWorker</code></li>
  <li>Use a While loop to wait for the thread / <code>BackgroundWorker</code> to finish.  For the thread, I wait for <code>IsAlive</code> to become false, for the <code>BackgroundWorker</code>, I toggle a boolean variable.</li>
  <li>I let the user know the process is finished.</li>
  </ol>
  
  <p>The problem is in #4.</p>
  
  <p>Doing a while loop with no code in it, or a <code>Thread.Sleep(0)</code> leaves the UI blocked (<code>Thread.Sleep(0)</code> makes the program take 100% of the program resources as well)</p>
  
  <p>So I do:</p>
  
  <pre><code>while (!thread.IsAlive)
     Thread.Sleep(1);
  </code></pre>
  
  <p>-or-</p>
  
  <pre><code>while (bProcessIsRunning)
     Thread.Sleep(1);
  </code></pre>
  
  <p>which blocks the UI.</p>
  
  <p>If I call <code>Application.DoEvents()</code> there, the UI is updated (though it's clickable, so I have to disable the entire form while this process runs).</p>
  
  <p>If I run the process synchronously, I still need to create some sort of way for the UI to be updated (in my mind, a <code>DoEvents</code> call) so it doesn't appear locked up.</p>
  
  <p>What am I doing wrong?</p>