LA.NET [EN]

Apr 05

This is the last post in the asynchronous action pattern series. In this post, we’re going to present the (so called) “delegate” pattern. This is really similar to the “event” pattern. The difference is that, in this case, we return a parameterless delegate from our begin method which will be called when all the asynchronous operations end.

To illustrate this pattern, we’re going to update the previous example. Here’s the final code:

public Func<ActionResult> GetHtml(String url) {
  var req = WebRequest.Create(url);
  req.Method = "GET";
  AsyncManager.RegisterTask(cb => req.BeginGetResponse(cb, null),
     ar => {
               var response = req.EndGetResponse(ar);
               using (var reader =
                      new StreamReader(response.GetResponseStream())) {
                  ViewData["contents"] = reader.ReadToEnd();
                }
              }
            );

return () => View(“Index”);
}

When compared with the “event” pattern, you can quickly see that:

  • the begin method returns a parameterless delegate which will be called when all the asynchronous operations end;
  • since we can’t pass any parameters to our custom callback method, we write the HTML directly to the ViewData dictionary;
  • we use a Lambda expression since the view we’re rendering doesn’t have the same name as the action method (if that was the case, we could simply return a reference to the View method, ie, we could simply write return View;).

And that’s all for today. More about the MVC framework on the next posts. Keep tuned!

1 comment so far

  1. YUIYUI
    3:07 pm - 11-19-2009

    YUIYU