In C#, if I want to deterministically clean up non-managed resources, I can use the \"using\" keyword. But for multiple dependent objects, this ends up nesting further and furt
I have implemented solutions like Michael Meadows's before, but his StreamWrapper
code doesn't take into account if the Dispose()
methods called on the member variables throw an exception for one reason or another, the subsequent Dispose()
es will not be called and resources could dangle. The safer way for that one to work is:
var exceptions = new List();
try
{
this.sr.Dispose();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
this.bs.Dispose();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
this.fs.Dispose();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
}