背景
我有一个 Windows 服务,它使用各种第三方 DLL 来处理 PDF 文件。这些操作可能会使用相当多的系统资源,并且在发生错误时偶尔会出现内存泄漏。DLL 是围绕其他非托管 DLL 的托管包装器。
当前解决方案
在一种情况下,我已经通过在专用控制台应用程序中包装对其中一个 DLL 的调用并通过 Process.Start() 调用该应用程序来缓解此问题。如果操作失败并且存在内存泄漏或未释放的文件句柄,这并不重要。该过程将结束,操作系统将恢复句柄。
我想将相同的逻辑应用于我的应用程序中使用这些 DLL 的其他地方。但是,我对向我的解决方案添加更多控制台项目并编写更多样板代码调用 Process.Start() 并解析控制台应用程序的输出并不感到非常兴奋。
新解决方案
专用控制台应用程序和 Process.Start() 的一个优雅替代方案似乎是使用 AppDomains,如下所示:http: //blogs.geekdojo.net/richard/archive/2003/12/10/428.aspx。
我在我的应用程序中实现了类似的代码,但单元测试并没有希望。我在单独的 AppDomain 中为测试文件创建了一个 FileStream,但不释放它。然后我尝试在主域中创建另一个 FileStream,但由于未释放的文件锁而失败。
有趣的是,向工作域添加一个空的 DomainUnload 事件会使单元测试通过。无论如何,我担心创建“工人”AppDomains 可能无法解决我的问题。
想法?
编码
/// <summary>
/// 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.
/// </summary>
public T RunInAppDomain<T>( Func<T> func )
{
AppDomain domain = AppDomain.CreateDomain ( "Delegate Executor " + func.GetHashCode (), null,
new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory } );
domain.DomainUnload += ( sender, e ) =>
{
// 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 ( "result" );
}
finally
{
AppDomain.Unload ( domain );
}
}
public void RunInAppDomain( Action func )
{
RunInAppDomain ( () => { func (); return 0; } );
}
/// <summary>
/// Provides a serializable wrapper around a delegate.
/// </summary>
[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 ( "result", _delegate.DynamicInvoke () );
}
}
单元测试
[Test]
public void RunInAppDomainCleanupCheck()
{
const string path = @"../../Output/appdomain-hanging-file.txt";
using( var file = File.CreateText ( path ) )
{
file.WriteLine( "test" );
}
// verify that file handles that aren't closed in an AppDomain-wrapped call are cleaned up after the call returns
Portal.ProcessService.RunInAppDomain ( () =>
{
// 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 ) )
{
}
}