I am in a situation where cleaning up unmanaged resources is a critical section. To solve this, I changed this...
void SomeMethod()
{
//work
using (var doc = SpreadsheetDocument.Open(results.FileName, true))
{
//use doc.
}
}
to this...
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();
}
}
}
}
Which, I believe, is an ugly and brittle solution. So, I changed it to the following...
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();
}
}
}
Is this custom solution robust? Can I improve on it? Is it guarantied to release any unmanaged resources like the built in Using statement?