The MVC framework: the “delegate” pattern for asynchronous actions

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!

Advertisements

~ by Luis Abreu on April 5, 2009.

One Response to “The MVC framework: the “delegate” pattern for asynchronous actions”

  1. YUIYU

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: