我处于清理非托管资源是关键部分的情况。为了解决这个问题,我改变了这个......
void SomeMethod()
{
//work
using (var doc = SpreadsheetDocument.Open(results.FileName, true))
{
//use doc.
}
}
对这个...
public static readonly object Locker = new object();
void SomeMethod()
{
//work
{//scoping doc
var doc = SpreadsheetDocument.Open(results.FileName, true);
try
{
//use doc
//At some point wrapping a critical section via lock(Locker)
}
finally
{
lock (Locker)
{
if (doc != null) ((IDisposable)doc).Dispose();
}
}
}
}
我相信,这是一个丑陋而脆弱的解决方案。所以,我将其更改为以下...
public static readonly object Locker = new object();
void SomeMethod()
{
//work
CustomUsingWithLocker(SpreadsheetDocument.Open(results.FileName, true), Locker, doc =>
{
//use doc
//At some point wrapping a critical section via lock(Locker)
});
}
public static void CustomUsingWithLocker<T>(T resource, object locker, Action<T> body)
where T : class, IDisposable
{
try
{
body(resource);
}
finally
{
lock (locker)
{
if (resource != null) resource.Dispose();
}
}
}
这个定制解决方案是否可靠?我可以改进它吗?是否保证释放任何非托管资源,如内置的 Using 语句?