Skip to content

Instantly share code, notes, and snippets.

@dahlbyk
Created December 7, 2009 04:41
Show Gist options
  • Save dahlbyk/250617 to your computer and use it in GitHub Desktop.
Save dahlbyk/250617 to your computer and use it in GitHub Desktop.
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