Created
          June 4, 2012 13:20 
        
      - 
      
- 
        Save leppie/2868328 to your computer and use it in GitHub Desktop. 
    CallWithEscapeContinuation Usage
  
        
  
    
      This file contains hidden or 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.Linq; | |
| class Program | |
| { | |
| sealed class EscapeContinuation<T> : Exception | |
| { | |
| public T Value { get; private set; } | |
| public void Raise(T value) | |
| { | |
| Value = value; | |
| throw this; | |
| } | |
| } | |
| static R CallWithEscapeContinuation<R>(Func<Action<R>, R> call) | |
| { | |
| var ec = new EscapeContinuation<R>(); | |
| try | |
| { | |
| return call(ec.Raise); | |
| } | |
| catch (EscapeContinuation<R> c) | |
| { | |
| if (c == ec) | |
| { | |
| return c.Value; | |
| } | |
| else | |
| { | |
| throw; | |
| } | |
| } | |
| } | |
| static void Main(string[] args) | |
| { | |
| var index = CallWithEscapeContinuation<int>(ec => | |
| { | |
| Enumerable.Range(0, 100).Select(x => | |
| { | |
| if (x == 40) ec(x); | |
| return x; | |
| }).ToList(); | |
| return -1; | |
| }); | |
| Console.WriteLine(index); | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment