
November 3, 2009 18:29 by
Brian Keating |
A neat way of always cleaning up resources is to use Lambdas as data.
Take the following
Source
internal interface ITryCatchReport
{
void Try(Action<IServer> action);
}
internal class TryCatchReport : ITryCatchReport
{
public TryCatchReport(IServer server)
{
_server = server;
}
public void Try(Action<IServer> action)
{
try
{
action(_server);
}
catch (Exception e)
{
Trace.WriteLine(e.Message);
// Clean up resources
// Report errors
}
}
private IServer _server;
}
Usage
TryCatchReport safeInvoker = new TryCatchReport(_data.Server);
safeInvoker.Try(x =>
{
x.MakeInterfaceCall();
});
We are now guranteed that in the case of an exception that the resources will get cleaned up.
Usage with code blocks
If you wish to execute many statements in the action look at this sample.
private List<WFActionDefinition> GetActionDefinitions()
{
if (_actionDefinitions == null)
{
safeInvoker.Try(x =>
{
x.Do1();
x.DoSomething();
OtherFunc();
});
}
return _actionDefinitions;
}
About Brian Keating
Professional Software Developer, .NET / C++ / Java View all posts by
Brian Keating →