Skip to content

Instantly share code, notes, and snippets.

@SridharPasham
Last active June 24, 2019 07:50
Show Gist options
  • Save SridharPasham/8f768b44bb9f35d3f9c3 to your computer and use it in GitHub Desktop.
Save SridharPasham/8f768b44bb9f35d3f9c3 to your computer and use it in GitHub Desktop.
Execute Around Method pattern
using System;
using System.Collections.Generic;
namespace PatternsByVS
{
public class Resource
{
private Resource()
{
Console.WriteLine("Resource created...");
}
public void Op1()
{
Console.WriteLine("Op1.");
}
public void Op2()
{
Console.WriteLine("Op2.");
}
private void Close()
{
Console.WriteLine("Clean up Resource...");
}
public static void Use(Action<Resource> block)
{
var resource = new Resource();
try
{
block(resource);
}
finally
{
resource.Close();
}
}
}
public class program
{
public static void Main(string[] args)
{
for (int i = 0; i < 3; i++)
{
// This way client will have only way to use resource and
// clean up of the resource is guaranteed. Even if exception happens in Op methods.
Resource.Use((resource) => {
resource.Op1();
resource.Op2();
});
}
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment