Pitfalls of (Mis)Using C# Iterators to Implement Coroutines

前端 未结 4 623
刺人心
刺人心 2021-01-31 20:32

I am writing refactoring a Silverlight program to consumes a portion of its existing business logic from a WCF service. In doing so, I\'ve run into the restriction in Silverligh

4条回答
  •  臣服心动
    2021-01-31 21:31

    I didn't read your whole thing.

    They use this strategy in CCR robotics studio, and a number of other projects use this strategy. An alternative is to use LINQ, see e.g. this blog for a description. The Reactive framework (Rx) is kinda built along these lines.

    Luca mentions in his PDC talk that perhaps future version of C#/VB may add async primitives to the language.

    In the meantime, if you can use F#, it is a winning strategy. Right now what you can do with F# here blows everything else right out of the water.

    EDIT

    To quote the example from my blog, suppose you have a WCF client that you want to call a couple methods on. The synchronous version might be written as

    // a sample client function that runs synchronously 
    let SumSquares (client : IMyClientContract) = 
        (box client :?> IClientChannel).Open() 
        let sq1 = client.Square(3) 
        let sq2 = client.Square(4) 
        (box client :?> IClientChannel).Close() 
        sq1 + sq2 
    

    and the corresponding async code would be

    // async version of our sample client - does not hold threads 
    // while calling out to network 
    let SumSquaresAsync (client : IMyClientContract) = 
        async { do! (box client :?> IClientChannel).OpenAsync() 
                let! sq1 = client.SquareAsync(3) 
                let! sq2 = client.SquareAsync(4) 
                do! (box client :?> IClientChannel).CloseAsync() 
                return sq1 + sq2 } 
    

    No crazy callbacks, you can use control constructs like if-then-else, while, try-finally, etc, write it almost exactly like you write straight-line code, and everything work, but now it's async. It's very easy to take a given BeginFoo/EndFoo pair of methods and make the corresponding F# async methods for use in this model.

提交回复
热议问题