title: Workflow background thread - how to wait
body: <p>I have a persistent workflow (runned by WorkflowApplication class) and I need to unit test correctness of runnung this workflow. </p>
  
  <p>I am running workflow from unit test and all runs fine, except I receive error message in output window: </p>
  
  <blockquote>
    <p>System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain. This can happen if the test(s) started a thread but did not stop it. Make sure that all the threads started by the test(s) are stopped before completion.</p>
  </blockquote>
  
  <p>I want to test results of workflow run after it was persisted and unloaded, so I use code like this:</p>
  
  <pre><code>AutoResetEvent waitHandle = new AutoResetEvent(false);
  WorkflowApplication wfApp = new WorkflowApplication(workflowTypeInstance, inputs);
  wfApp.Unloaded = delegate(WorkflowApplicationEventArgs e)
  {   
      waitHandle.Set();
  };
  // ....
  wfApp.Run();
  waitHandle.WaitOne();
  </code></pre>
  
  <p>The problem is, that workflow application background thread does not terminate right after unload of workflow, but test method does. This causes the error message in output window.</p>
  
  <p>Any idea / approach / point how to wait for background thread termination?</p>