Asynchronous programming of dark magic in ASP. NET MVC

Source: Internet
Author: User

Reference: http://www.codeguru.com/csharp/.net/net_asp/mvc/working-with-asynchronous-operations-in-asp.net-mvc.htm

 

ASP. net MVC 4 adds the async keyword to make asynchronous programming very easy, but this article is not about this, but about the implementation of another ASP. net MVC asynchronous programming method, I guess many people have not seen it, so I call it dark magic (uncommon but probably more powerful stuff ).

First look at a piece of code:

public void Foo() {   A();   B();   C();}

 

If a (), B (), and C () are remote method calls and the three methods do not affect each other, then Foo () the time when the method is executed is equal to the sum of the time when the three methods are executed, because the three methods are executed serially.

This is the time for asynchronous programming to shine. If asynchronous programming is used, the execution time of the Foo () method is equal to the maximum execution time of the Methods A, B, and C.

How does one implement asynchronous programming in ASP. net mvc (ASP. net mvc 4 async is not taken into account )?

Code:

public class HomeController: AsyncController{   public void IndexAsync()   {   }   public ActionResult IndexCompleted(...)   {   }}

Observe that the controller homecontroller inherits from asynccontroller and has two more actions. The suffix of the first action name must be async. asynchronous operations are performed in this action method. The second action ends with completed, indicating what is done after the asynchronous operation is completed.

Suppose we want to implement an application for obtaining Google RSS news and msn rss news. The code is roughly as follows:

public class HomeController : AsyncController{    private void GetGoogleNews()    {    }     private void GetMSNNews()    {    }     public void IndexAsync()    {    }     public ActionResult IndexCompleted()    {    }}

Obviously, obtaining Google News and MSN news can be executed asynchronously.

The implementation of indexasync is as follows:

public void IndexAsync(){    AsyncManager.OutstandingOperations.Increment(2);    Task.Factory.StartNew(() => GetGoogleNews());     Task.Factory.StartNew(() => GetMSNNews()); }

It's a little strange. Let's just talk about the first line of code. increment (2) indicates that there are two asynchronous tasks to be executed.

The implementation of getgooglews and getmsnnews is as follows:

private void GetGoogleNews(){    XmlReader reader = XmlReader.Create("http://news.google.co.in/news?pz=1&cf=all&ned=in&hl=en&output=rss");    Rss20FeedFormatter formatter = new Rss20FeedFormatter();    formatter.ReadFrom(reader);    reader.Close();    AsyncManager.Parameters.Add("GoogleNews", formatter.Feed.Items);    AsyncManager.OutstandingOperations.Decrement();} private void GetMSNNews(){    XmlReader reader = XmlReader.Create("http://msn.com/rss/news.aspx");    Rss20FeedFormatter formatter = new Rss20FeedFormatter();    formatter.ReadFrom(reader);    reader.Close();    AsyncManager.Parameters.Add("MSNNews", formatter.Feed.Items);    AsyncManager.OutstandingOperations.Decrement();}

Follow asyncmanager. Parameters. Add (...). It uses the parameter set of the asyncmanager object to save the result data after the asynchronous task is executed.

Then the asyncmanager. outstandingoperations. decrement () method is used to indicate that the asynchronous task to be executed has completed another one.

The following is the implementation of indexcompleted:

public ActionResult IndexCompleted(IEnumerable<SyndicationItem> GoogleNews, IEnumerable<SyndicationItem> MSNNews){    List<SyndicationItem> allItems = new List<SyndicationItem>();    allItems.AddRange(GoogleNews);    allItems.AddRange(MSNNews);    allItems.Sort(CompareDates);    ViewBag.FeedItems = allItems;    return View();}

Note that the ienumerable <syndicationitem> googlenews and ienumerable <syndicationitem> msnnews parameters correspond to the two result data saved in the parameter combination of the asyncmanager object above.

Finally, the front-end code is implemented:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %><%@ Import Namespace="System.ServiceModel.Syndication" %> <!DOCTYPE html> 

Enter a URL similar to the following:

http://localhost:4078/home/index

Striving for self-improvement!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.