Created
December 7, 2009 04:41
-
-
Save dahlbyk/250617 to your computer and use it in GitHub Desktop.
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
static void Main(string[] args) | |
{ | |
var f = Fault(() => Console.WriteLine("Okay"), | |
() => Console.WriteLine("Fault")); | |
f(); | |
Console.WriteLine(); | |
var g = Fault(() => { throw new Exception("Oops"); }, | |
() => Console.WriteLine("Fault")); | |
try | |
{ | |
g(); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex); | |
} | |
} | |
static Action Fault(Action protectedBlock, Action faultHandler) | |
{ | |
return () => Faulter.Fault(protectedBlock, faultHandler); | |
} | |
private class Faulter : IDisposable | |
{ | |
private Action faultHandler; | |
public Faulter(Action faultHandler) | |
{ | |
this.faultHandler = faultHandler; | |
} | |
public void Dispose() | |
{ | |
faultHandler(); | |
} | |
public static void Fault(Action protectedBlock, Action faultHandler) | |
{ | |
GetFaultEnumerator(protectedBlock, faultHandler).MoveNext(); | |
} | |
private static IEnumerator<bool> GetFaultEnumerator(Action protectedBlock, Action faultHandler) | |
{ | |
using (var f = new Faulter(faultHandler)) | |
{ | |
protectedBlock(); | |
yield return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment