Last active
June 24, 2019 07:50
-
-
Save SridharPasham/8f768b44bb9f35d3f9c3 to your computer and use it in GitHub Desktop.
Execute Around Method pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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