Tech Off Thread

3 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

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#!

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.