title: Replacing Process.Start with AppDomains
body: <p><strong>Background</strong></p>
  <p>I have a Windows service that uses various third-party DLLs to perform work on PDF files.  These operations can use quite a bit of system resources, and occasionally seem to suffer from memory leaks when errors occur.  The DLLs are managed wrappers around other unmanaged DLLs.</p>
  <p><strong>Current Solution</strong></p>
  <p>I'm already mitigating this issue in one case by wrapping a call to one of the DLLs in a dedicated console app and calling that app via Process.Start().  If the operation fails and there are memory leaks or unreleased file handles, it doesn't really matter.  The process will end and the OS will recover the handles.</p>
  <p>I'd like to apply this same logic to the other places in my app that use these DLLs.  However, I'm not terribly excited about adding more console projects to my solution, and writing even more boiler-plate code that calls Process.Start() and parses the output of the console apps.</p>
  <p><strong>New Solution</strong></p>
  <p>An elegant alternative to dedicated console apps and Process.Start() seems to be the use of AppDomains, like this:  <a href="https://web.archive.org/web/20100620111059/http://blogs.geekdojo.net/richard/archive/2003/12/10/428.aspx" rel="nofollow noreferrer">http://blogs.geekdojo.net/richard/archive/2003/12/10/428.aspx</a></p>
  <p>I've implemented similar code in my application, but the unit tests have not been promising.  I create a FileStream to a test file in a separate AppDomain, but don't dispose it.  I then attempt to create another FileStream in the main domain, and it fails due to the unreleased file lock.</p>
  <p>Interestingly, adding an empty DomainUnload event to the worker domain makes the unit test pass.  Regardless, I'm concerned that maybe creating &quot;worker&quot; AppDomains won't solve my problem.</p>
  <p>Thoughts?</p>
  <p><strong>The Code</strong></p>
  <pre><code>/// &lt;summary&gt;
  /// Executes a method in a separate AppDomain.  This should serve as a simple replacement
  /// of running code in a separate process via a console app.
  /// &lt;/summary&gt;
  public T RunInAppDomain&lt;T&gt;( Func&lt;T&gt; func )
  {
      AppDomain domain = AppDomain.CreateDomain ( &quot;Delegate Executor &quot; + func.GetHashCode (), null,
          new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory } );
          
      domain.DomainUnload += ( sender, e ) =&gt;
      {
          // this empty event handler fixes the unit test, but I don't know why
      };
  
      try
      {
          domain.DoCallBack ( new AppDomainDelegateWrapper ( domain, func ).Invoke );
  
          return (T)domain.GetData ( &quot;result&quot; );
      }
      finally
      {
          AppDomain.Unload ( domain );
      }
  }
  
  public void RunInAppDomain( Action func )
  {
      RunInAppDomain ( () =&gt; { func (); return 0; } );
  }
  
  /// &lt;summary&gt;
  /// Provides a serializable wrapper around a delegate.
  /// &lt;/summary&gt;
  [Serializable]
  private class AppDomainDelegateWrapper : MarshalByRefObject
  {
      private readonly AppDomain _domain;
      private readonly Delegate _delegate;
  
      public AppDomainDelegateWrapper( AppDomain domain, Delegate func )
      {
          _domain = domain;
          _delegate = func;
      }
  
      public void Invoke()
      {
          _domain.SetData ( &quot;result&quot;, _delegate.DynamicInvoke () );
      }
  }
  </code></pre>
  <p><strong>The unit test</strong></p>
  <pre><code>[Test]
  public void RunInAppDomainCleanupCheck()
  {
      const string path = @&quot;../../Output/appdomain-hanging-file.txt&quot;;
  
      using( var file = File.CreateText ( path ) )
      {
          file.WriteLine( &quot;test&quot; );
      }
  
      // verify that file handles that aren't closed in an AppDomain-wrapped call are cleaned up after the call returns
      Portal.ProcessService.RunInAppDomain ( () =&gt;
      {
          // open a test file, but don't release it.  The handle should be released when the AppDomain is unloaded
          new FileStream ( path, FileMode.Open, FileAccess.ReadWrite, FileShare.None );
      } );
  
      // sleeping for a while doesn't make a difference
      //Thread.Sleep ( 10000 );
  
      // creating a new FileStream will fail if the DomainUnload event is not bound
      using( var file = new FileStream ( path, FileMode.Open, FileAccess.ReadWrite, FileShare.None ) )
      {
      }
  }
  </code></pre>