Technology is great. I am in a car (relax, no, I'm not driving at the moment!) and decided this
is a great time to put that wireless network to use and blog this finally.
Inspired by Ruby and Anonymous delegates in C#, in some special cases, you can manage proper
resource clean up, and/or, execution of pre and post operations. We know that there is no guarantee
when finalize is called and there is no way to insist that our users call Dispose. What if calling Dispose
is very critical or if you have to do some post-processing in your code. Well, here is a way to do just that.
using System;
using System.Collections.Generic;
using System.Text;
namespace ResourceCleanExample
{
public delegate void ResourceUseHelper(Resource resource);
public class Resource : IDisposable
{
private Resource() { Console.WriteLine("Pre-procesing is taken care..."); }
public static void UseResource(ResourceUseHelper resourceHelper)
{
Resource resource = new Resource();
try
{
resourceHelper(resource);
}
finally
{
resource.Dispose();
}
}
#region IDisposable Members
public void Dispose() // In addition follow the Dispose Design Pattern...
{
Console.WriteLine("Any cleanup or post-processing is taken care...");
}
public void someOp1() { Console.WriteLine("Some op1 done..."); }
public void someOp2() { Console.WriteLine("Some op2 done..."); }
#endregion
}
public class Program
{
static void Main(string[] args)
{
Resource.UseResource(delegate(Resource r)
{
r.someOp1();
r.someOp2();
}
);
}
}
}
The output from above code is:
Pre-procesing is taken care...
Some op1 done...
Some op2 done...
Any cleanup or post-processing is taken care...