How work with AsyncController in asp.net MVC 3?

2.8k views Asked by At

Search several blogs about it but always are same examples.

I dunno if misunderstood or'm not knowing use but see no parallel process when work with AsyncController.

The following tests performed

Create a new project of type Asp.net MVC

HomeController.cs

public void IndexAsync()
{
    AsyncManager.OutstandingOperations.Increment();
    var bg = new BackgroundWorker();
    bg.DoWork += (o, e) => GetEntriesBlog();
    bg.RunWorkerCompleted += (o, e) =>
                                    {
                                        AsyncManager.Parameters["items"] = e.Result;
                                        AsyncManager.OutstandingOperations.Decrement();
                                    };
    bg.RunWorkerAsync();

    ViewBag.Message = "Modify this template to kick-start your ASP.NET MVC application.";

}

public ActionResult IndexCompleted(IEnumerable<SyndicationItem> items)
{
    return View(items);
}

[NonAction]
public IEnumerable<SyndicationItem> GetEntriesBlog(int page = 0)
{
    using (var reader = XmlReader.Create("http://blog.bindsolution.com/rss"))
    {
        Thread.Sleep(20000);
        var rssData = SyndicationFeed.Load(reader);
        if (rssData != null)
        {
            return (from item in rssData.Items
                    orderby item.PublishDate descending
                    select item).Take(3).Skip(3 * page).ToList();
        }
        return null;
    }
}

Always delay 20 seconds browsing the site!

I was thinking of using PartialView AsyncController in to perform this task. Work?

1

There are 1 answers

1
Hector Correa On BEST ANSWER

I think you are misunderstanding what the Asynchronous Background worker would do.

If the operation takes 20 seconds using a background worker will not reduce that time or make the view render any faster. Using an asynchronous operations will free up the worker process on the server to process other requests while this long running request keep chugging along.

In your case I think you should create a very simple view that returns quickly to the user and kick of the long running operation as an asynch request from the client. For example, render the fast portions of your page (e.g. header, menus, et cetera) and make an AJAX request for the blog entries.

Depending on the nature of the code in GetEntriesBlog you might not need to make the controller operation asynchronous. In theory, since most of the time in this method will be spend waiting for the HTTP GET request to http://blog.bindsolution.com/rss to complete, it might be a good idea but in practice those things need to be bench marked (and perhaps under heavy load) to make sure you are getting the benefit that you expect. Keep in mind that your server code side will be more complex (and harder to maintain) if you make it asynch. I would suggest you go this route only if you do get a significant benefit.