Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the event-based Asynchronous Mode of ASP.NET and Asynchronous Action

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "ASP.NET event-based asynchronous mode and how to implement asynchronous Action", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to implement the event-based asynchronous mode of ASP.NET and asynchronous Action.

Although asynchronous Action is not directly supported in ASP.NET MVC 1, asynchronous request processing in ASP.NET is officially supported in ASP.NET MVC 2 and made available to developers in an easy-to-use way. Unfortunately, due to language constraints, this way of use is still somewhat inconvenient, and this is the opportunity for F# to show its talents.

Event-based asynchronous mode

When it comes to the asynchronous programming model in .NET, what .NET programmers are most familiar with is the Begin/End method. For example, in the WebRequest class, there is a pair of methods:

Var request = WebRequest.Create ("http://www.51cto.com/"); request.BeginGetResponse (ar = > {var response = request.EndGetResponse (ar); / / use the response object}, null))

After calling the BeginGetResponse method of the WebRequest object, the current calling thread will not be blocked, but after the asynchronous operation is completed, a callback function (that is, the code constructed using the Lambda expression here is fast) will be called to notify. Calling the EndGetResponse method in this callback function will get a WebResponse object as a result.

In this asynchronous operation, thanks to the great IOCP, we can use a very small number of threads to initiate thousands of connections at the same time (literally, I have experimented with Comet in IIS and set up more than 2w connections to communicate at the same time). In fact, however, there is also an event-based asynchronous pattern (Event-based Asynchronous Pattern,EAP) in .NET. One of the typical examples of event-based asynchronous programming is the WebClient class:

Var client = new WebClient (); client.DownloadStringCompleted + = (sender, args) = > {var html = args.Result; / /...}; client.DownloadStringAsync (new Uri ("http://www.51cto.com/"));)

The key to an event-based asynchronous pattern is that it uses events as a notification mechanism at the end of work. It is significantly different from Begin/End 's asynchronous model. For example, when an error occurs, the Begin/End model throws an exception when the End method is called, while in the case of an event-based asynchronous pattern, it uses the Exception property of the event parameter to tell the programmer if an exception occurred. If the Exception property is null, everything is fine, otherwise it returns the exception that occurred during the asynchronous call.

Using Asynchronous Action in ASP.NET MVC

My Hack used the Begin/End asynchronous programming model, while ASP.NET MVC 2 used the event-based asynchronous mode. Around this pattern, ASP.NET MVC's AsyncController also provides related auxiliary methods to make it relatively easy to write asynchronous Action. Here I will directly quote the example on MSDN to illustrate the problem. First, we prepare a normal synchronous Action:

Public class PortalController: Controller {public ActionResult News (string city) {var newnewsService = new NewsService (); var headlines = newsService.GetHeadlines (city); return View (headlines);}}

The equivalent asynchronous Action is:

Public class PortalController: AsyncController {public void NewsAsync (string city) {AsyncManager.OutstandingOperations.Increment (); var newnewsService = new NewsService (); newsService.GetHeadlinesCompleted + = (sender, e) = > {AsyncManager.Parameters ["headlines"] = e.Value; AsyncManager.OutstandingOperations.Decrement ();}; newsService.GetHeadlinesAsync (city) } public ActionResult NewsCompleted (string [] headlines) {return View ("News", headlines);}}

Obviously, asynchronous Action is also a standard two-stage call, but this two-stage call is made by a special "convention". When using asynchronous Action in ASP.NET MVC 2, you first need to inherit the AsyncController class and construct the XyzAsync and XyzCompleted methods, the former returning void and the latter returning ActionResult--, which represents an asynchronous Action named Xyz.

ASP.NET MVC 2 also provides some support for asynchronous Action development, which comes from AsyncManager. Before initiating an asynchronous operation, we can call the Increment method of its OutstandingOperations object to indicate that "several asynchronous operations" are required.

After each asynchronous operation ends, that is, in the event handler, the corresponding Decrement method is called. This method means "an asynchronous operation has been completed," and after Decrement reaches zero, ASP.NET MVC will know that all asynchronous operations have been completed, so it will call the XynCompleted method to get the desired ActionResult object.

As for the parameters required by the XyzCompleted method, you can see from the code that you are "transitioning" through the Parameters collection of AsyncManager. What is not ideal here is the use of strings as a "weak type". Assuming that the parameter name changes, the corresponding string needs to be changed as well.

Choose Begin/End or event-based asynchronous mode?

Obviously, you can use either Begin/End or event-based asynchronous programming patterns in ASP.NET MVC, because ASP.NET MVC itself operates asynchronously based on the behavior of AsyncManager. In ASP.NET MVC, however, event-based asynchronous patterns seem to be more important. I guess this is due to the difference in the behavior of the two asynchronous modes for exceptions.

As I mentioned earlier, when using the Begin/End asynchronous pattern, if an error occurs, an exception is thrown when the End method is called. You know that throwing an exception in a callback function is one of the most dangerous situations in asynchronous programming. If it is not captured correctly, it will crash the entire process-- of course, we can also set it to "ignore" in the configuration file, but this is obviously not appropriate, for example, it will cause the request to never end until it times out, and may cause resource leakage.

In contrast, using an event-based asynchronous pattern does not cause this problem, because in this case, the event must be called correctly, and the exception is always safely stored in the Exception property of the event parameter. Therefore, using Begin/End requires additional try...catch protection, and using an event-based asynchronous programming mode makes the code a little more streamlined.

Of course, it is simple to use, only because those exceptions have been handled by the "provider" of the asynchronous operation. Just imagine, the reason why WebClient can expose exceptions through event parameters must be because try...catch is used internally. By the same token, if we are to implement an event-based asynchronous pattern, such as NewsService above, exceptions must be handled carefully.

At this point, I believe you have a better understanding of "how to implement ASP.NET event-based asynchronous mode and asynchronous Action". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report