Tech Off Thread

3 posts

Asynchronous Programming using LINQ Syntax

Back to Forum: Tech Off
  • User profile image
    Andrew Davey

    After reading
    I created a program that enables creating multiple web requests asynchronously. Even the response streams are read using non-blocking IO!

    var requests = new[]

    var pages =
        from request in requests select
    // essentially we are defining the computation here 
    // it does NOT run here
            from response in request.GetResponseAsync()
            let stream = response.GetResponseStream()
            from html in stream.ReadToEndAsync()
            select new { html, response };

    foreach (var page in pages)
        page(d => // do this when the page data is ready
            Console.WriteLine(d.html.Substring(0, 40));
    } // for loop kicks off the calls and does NOT block the main thread.


    The code reads like it is synchronous, but it's really not! You get the benefit of easy to read and write code that is also uses non-blocking IO. So it's not using up threads waiting for each request to return.

    Check out my blog post for the code that implements the Continuation Monad and provides the methods required to enable the LINQ syntax.
    There is no explicit thread at all in my code. It uses the BeginXXX/EndXXX async methods.

    I think it's amazing how LINQ can be leveraged to things other than querying data - All thanks to its monadic under-pinings.

  • User profile image

    Indeed this is one of the benefits of LINQ... - although you still have to create some extension methods (that you are using) which you have hidden away in this post Smiley

  • User profile image

    This reminds me of the example that the F# folks wrote about in the "Expert F#" book (page 366 - Fetching Three Web Pages Simultaneously).  Nice job converting that to C#!

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.