Do not directly use async and await on the page events of ASP. NET 4.5 BETA.

Source: Internet
Author: User
Document directory
  •  
  • Problems Found
  • Errors Caused by direct use of async on events
  • Usetaskfriendlysynchronizationcontext and causes of errors
  • Currently, the correct method is used.

Welcome to my blog to read standalone: http://www.dozer.cc/2012/03/async-and-await-in-asp-net-beta/

Problems Found

In my previous articleApplication of async and await on the Web, I mentioned a strange configuration in the web. config of Asp.net 4.5:

<appSettings>  <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /></appSettings>

InStack OverflowFinally, someone answered me.

After reading the replies from others, I found the problems in my previous article.

This usage in the following code is incorrect:

protected async void Page_Load(object sender, EventArgs e){    WebClient client = new WebClient();    var result1 = await client.DownloadStringTaskAsync("http://www.website.com");    WebClient client2 = new WebClient();    var result2 = await client.DownloadStringTaskAsync(result1);    //do more}

 

Error code segment 1 caused by direct use of async on the event:
public partial class WebForm1 : System.Web.UI.Page{    protected string Msg { get; set; }    protected async void Page_Load(object sender, EventArgs e)    {        using (WebService service = new WebService())        {            Msg = await service.Method1TaskSync();        }    }    protected async void Button_Test_Click(object sender, EventArgs e)    {        using (WebService service = new WebService())        {            Msg = await service.Method2TaskSync();        }    }}

What is the final MSG value? Which method should return the value?

If Asynchronization is removed, the answer must be method2. What about asynchronous?

Here async and await are used to implement Asynchronization, so the logic order should be the same as the code order.

But the two events in the above Code will be executed together! Some problems have occurred!

To sum up the above Code: When the page_load event and other events on the page use async and await, errors in execution order and deadlocks may occur. They are not executed in order.

 

Code Segment 2:
<appSettings>  <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /></appSettings>

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="AsyncAwait.WebForm1"    Async="true" %><!DOCTYPE html>

The back-end code is the same as the above Code, except that the configuration of usetaskfriendlysynchronizationcontext is changed to true, and the data is displayed on the page.

After the execution, we found that the content cannot be displayed at all, and the page was output before the asynchronous execution was completed.

 

Usetaskfriendlysynchronizationcontext and causes of errors

In fact, I have already explained all in my answers from foreigners. Here I am mainly about translation + streamlining.

 

Usetaskfriendlysynchronizationcontext:

The Asynchronous Method Used by Asp.net in earlier versions does not comply with CLR specifications, but only the registerasynctask method complies with CLR specifications.

Therefore, in Asp.net 4.5, this new configuration is added to disable previously non-conforming features. If you set this configuration to true, all other asynchronous schemes will be invalidated. (Code segment 2 mainly demonstrates this phenomenon)

 

Cause of error:

Async and await keywords use synchronizationcontext at the underlying layer to implement Asynchronization. (I have never studied the specific principles)

This solution first does not comply with CLR specifications, and also causes many problems. (Code snippet 1 mainly demonstrates one of the problems)

 

Currently, the correct method is used.

First, we recommend that you set usetaskfriendlysynchronizationcontext to true.

In addition, the correct syntax is as follows:

public partial class WebForm1 : System.Web.UI.Page{    protected string Msg { get; set; }    protected void Page_Load(object sender, EventArgs e)    {        RegisterAsyncTask(new PageAsyncTask(Method1));    }    private async Task Method1()    {        using (WebService service = new WebService())        {            Msg = await service.HelloWorldTaskSync();        }    }    protected void Button_Test_Click(object sender, EventArgs e)    {        RegisterAsyncTask(new PageAsyncTask(Method2));    }    private async Task Method2()    {        using (WebService service = new WebService())        {            Msg = await service.HelloWorldTaskSync();        }    }}

If asynchronous writing is required, you must use the registerasynctask method. The test results show that multiple calls are supported and executed in order.

 

As a foreigner said, they also want to add async to the event, but it is not implemented for technical reasons. I hope it can be implemented in the official or future version!

 

References:

Http://stackoverflow.com/questions/9562836/whats-the-meaning-of-usetaskfriendlysynchronizationcontext

Http://social.msdn.microsoft.com/Forums/en-NZ/async/thread/b2e8c51e-2808-46d0-92e9-b825321d0af8

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.