Asynchronous programming of ASP. NET MVC

Source: Internet
Author: User

Asynchronous programming of ASP. NET MVC

In the previous article ASP. NET asynchronous programming. Now ASP. NET has been developed to MVC 3. How should we implement asynchronous programming in MVC? Rest assured that. NET Framework has provided us with asynccontroller (asynchronous Controller), which can be used to implement asynchronous MVC programming. The following is a brief introduction to its usage.

To use asynccontroller for asynchronous programming, follow these steps.

1. Do not derive a controller from the Controller, but from the asynccontroller.

2. Create two methods for action. The two methods end with async and completed respectively. * ** The async method returns void, and the *** completed method returns the actionresult instance. Although an operation is composed of two methods, you can use the same URL as the synchronization operation method to access it (for example, portal/news? City = Seattle ). Other methods (such as redirecttoaction and renderaction) will reference the operation method according to news instead of newsasync. Parameters passed to *** sasync use the common parameter binding mechanism. Pass
* ** The completed parameter uses the parameters dictionary.

 

Notes for using asynccontroller:

1. Use the outstandingoperations attribute to notify ASP. Net of the number of pending operations. This is necessary because ASP. Net cannot determine how many operations are started by the operation method or when these operations are completed. When the outstandingoperations attribute is zero, ASP. NET can call the *** completed method to complete the entire asynchronous operation.

2. If you want to apply features to asynchronous operation methods, apply them to the actionasync method instead of the actioncompleted method. Ignore the features of the actioncompleted method.

Two new features have been added: asynctimeoutattribute and noasynctimeoutattribute. These features allow you to control the asynchronous timeout.

3. If an asynchronous operation method calls a service that uses the inmethod/endmethod mode to publish a method, the callback method (that is, the method passed to the begin method as an asynchronous callback parameter) it may not be caused by ASP.. net. In this case, httpcontext. Current is null, and a race condition may occur when the application accesses members of the asyncmanager class (such as parameters. To ensure that the httpcontext. Current instance has been accessed and the race condition is avoided, you can restore it by calling sync () from the callback method.
Httpcontext. Current.

 

Example 1: Call three event-based Asynchronous WebService instances in a method

        private readonly ServiceClient _client = new ServiceClient();        public void AsynchronousAsync() {            ViewData["Title"] = "Parallel asynchronous calls";            AsyncManager.OutstandingOperations.Increment(3);            string city = "Seattle";            _client.GetHeadlinesCompleted += (sender, e) => {                AsyncManager.Parameters["headlines"] = e.Result;                AsyncManager.OutstandingOperations.Decrement();            };                        _client.GetHeadlinesAsync(city);            _client.GetScoresCompleted += (sender, e) => {                AsyncManager.Parameters["scores"] = e.Result;                AsyncManager.OutstandingOperations.Decrement();            };            _client.GetScoresAsync(city);            _client.GetForecastCompleted += (sender, e) => {                AsyncManager.Parameters["forecast"] = e.Result;                AsyncManager.OutstandingOperations.Decrement();            };            _client.GetForecastAsync(city);        }        public ActionResult AsynchronousCompleted(NewsHeadline[] headlines, SportsScore[] scores, WeatherForecast[] forecast) {            return View("Common", new ViewModel {                Headlines = headlines,                Scores = scores,                Forecast = forecast            });        }

Complete: http://archive.msdn.microsoft.com/aspnetmvcsamples/Release/ProjectReleases.aspx? Releaseid = 3547

Example 2: Call an asynchronous WebService in begin/end Mode

        public void NewsAsync(string city)        {            AsyncManager.OutstandingOperations.Increment();            _client.BeginGetHeadlines(city, ar =>            {                if (ar.CompletedSynchronously)                {                    AsyncManager.Parameters["news"] =                        _client.EndGetHeadlines(ar);                    AsyncManager.OutstandingOperations.Decrement();                }                else                {                    AsyncManager.Sync(() =>                    {                        AsyncManager.Parameters["news"] =                        _client.EndGetHeadlines(ar);                        AsyncManager.OutstandingOperations.Decrement();                    });                }            }, null);        }        public ActionResult NewsCompleted(NewsHeadline[] headlines)        {            return View("Common", new ViewModel            {                Headlines = headlines            });        }
Related Article

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.