Apr 05

The MVC framework: simplifying the “event” pattern

Posted in ASP.NET MVC      Comments Off on The MVC framework: simplifying the “event” pattern

In the previous post, we’ve taken a look at the “event” pattern. In this post, we’re going to see how we can simplify the needed code for using this pattern. The AsyncManager exposes a RegisterTask method which simplifies the needed code when we decide to use this pattern. We’ll improve the previous example by using this method. Here’s the code:

public void 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())) {
                  AsyncManager.Parameters["contents"] = reader.ReadToEnd();


public ActionResult GetHtmlCompleted(String contents) {
  ViewData["contents"] = contents;
  return View("Index");

As you can see, the code is really similar to the one we’ve shown in the other post. The main difference is that with this helper method you’ll only need to worry with setting up the asynchronous action.

And that’s all for today. On the next post, we’ll talk about the latest option for having asynchronous actions in MVC controllers.