title: Error while unloading appdomain. (Exception from HRESULT: 0x80131015), inside Windows Service
body: <p>I receive this error in a windows service.
  This is the same service that I've previously discussed in my question <a href="https://stackoverflow.com/questions/13346899/thread-join-appears-to-return-false-incorrectly">here</a></p>
  
  <p>The code is revised to use <code>Parallel.ForEach</code> (my own version as this is a 3.5 windows service).  The reason for the Parallel use is down to the fact that it simply took too long to Unload each domain and running them in parallel should prove to be faster (appears to be even though there is only one thread that's doing each Unload?!).</p>
  
  <p>Based on other posts, I can only guess that this is somehow down to the fact I am using a <code>ThreadPool</code> <code>Thread</code> to <code>Unload</code> the <code>AppDomain</code>s.  I just can't see how to avoid it?</p>
  
  <pre><code>public partial class SomeService : ServiceBase
  {
      private Manager _appDomainManager;
  
      protected override void OnStop()
      {
          _appDomainManager.Dispose();
      }
  }
  
  public class Manager : IDisposable
  {
      public void Dispose()
      {
          Log.Debug("Disposing");
          Dispose(true);
          GC.SuppressFinalize(this);
      }
  
      protected virtual void Dispose(bool disposing)
      {
          if (_disposed) return;
          if (disposing)
          {
              // dispose managed resources
              Parallel.For(0, appdomains.Length, UnloadAppDomian);
          }
  
          _disposed = true;
      }
  }
  
  private UnloadAppDomain(int appDomainIndex);
  
  public static class Parallel35
  {
      public static void For(int start, int end, Action&lt;int&gt; action)
      {
          var waitHandles = new WaitHandle[end - start];
          for (int j = 0; j &lt; waitHandles.Length; j++)
          {
              waitHandles[j] = new ManualResetEvent(false);
          }
  
          for (int i = start; i &lt; end; i++)
          {
              int i1 = i - start;
              ThreadPool.QueueUserWorkItem(
                  state =&gt;
                  {
                      try
                      {
                          action((int) state);
                      }
                      finally
                      {
                          ((ManualResetEvent) waitHandles[i1]).Set();
                      }
                  }, i);
          }
          WaitHandle.WaitAll(waitHandles);
      }
  }
  </code></pre>