title: WPF Method to wait for DocumentCompleted Event
body: <p>I know this has <a href="https://stackoverflow.com/questions/583897/c-how-to-wait-for-a-webpage-to-finish-loading-before-continuing">been asked before</a>, but I don't think <a href="https://stackoverflow.com/questions/7295560/wait-for-webbrowser-to-finish-process">these solutions</a> are flexible. The <code>DocumentCompleted</code> event should be used to determine when the load has completed, not as a method for performing work. If you need to perform several different tasks that each have to navigate several times, placing the logic in the <code>DocumentCompleted</code> event turns it into a messy switch/case router that is hard to read and maintain.</p>
  
  <p>You need something that can actually wait during your method performing navigation so you can continue your task in the method you are already in. My first though is an actual Wait() method.</p>
  
  <p>I would think something like this is close:</p>
  
  <pre><code>void WaitForLoad()
      {
          isLoading = true;
          while (isLoading)
          {
              if (Application.Current == null) break;
              Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, (DispatcherOperationCallback)delegate(object unused) { return null; }, null);
          }
      }
  </code></pre>
  
  <p>And set Isloading to false in the <code>DocumentCompleted</code> event.</p>
  
  <p>You should be able to just call this method after whatever action will cause a pageload. It works, it has some issues. </p>
  
  <p>1)  it sends the CPU usage for the app up to 35% until the page has loaded, even if nothing else is happening. </p>
  
  <p>2)  if the application tries to close while its running, the loop will keep running and leave the app open with no windows, hence the need for the break when the app is null.</p>
  
  <p>Can this be fixed, or am I coming at this all the wrong way?</p>
  
  <p><strong>Edit</strong>: I tried implementing the ManualResetEvent solution below, but it led to several other issues that I am not sure can be resolved without creating a messier situation than the one above. Since the WebBrowser is on the UI, locking the thread stop the entire app. If the work is done on the background thread it can be locked, but then accessing the WebBrowser becomes very difficult.</p>