How to use async/await to achieve asynchronous page in asp.net webform?

We can now use the async/await key words in ASP.NET MVC 4.

public async Task<ActionResult> TestAsync()
{
    WebClient client = new WebClient();
    return Content(await client.DownloadStringTaskAsync("http://www.google.com"));
}

But how to use it in ASP.NET WebForms?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

One easy way is to just make your event handlers async. First, add the Async="true" parameter to the @Page directive, and then you should be able to write async event handlers as such:

protected async void Page_Load(object sender, EventArgs e)
{
  var client = new WebClient();
  var content = await client.DownloadStringTaskAsync("http://www.google.com");
  Response.Write(content);
}

I say “should be able to” because I haven’t actually tried this out myself. But it should work.

Update: This does not work for Page_Load (see this MSDN forum thread), but should work for other events such as button clicks.

Update: This does work for Page_Load in ASP.NET 4.5. Also, they added checks if you improperly use an async event handler. See this video for details.

Method 2

According to http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx the only reliable way to use async in web forms is to call Page.RegisterAsyncTask.

The code to support simple things like async Page_Load is extremely
complicated and not well-tested for anything beyond basic scenarios.

Using async with voids is not stable or reliable. However, all you
have to do is call Page.RegisterAyncTask – it’s not any trouble and
you’ll be in a better more flexible place

.

public void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(LoadSomeData));
}

public async Task LoadSomeData()
{
var clientcontacts = Client.DownloadStringTaskAsync("api/contacts");
var clienttemperature = Client.DownloadStringTaskAsync("api/temperature");

var contacts = Newtonsoft.Json.JsonConvert.DeserializeObject>(await clientcontacts);
var temperature = Newtonsoft.Json.JsonConvert.DeserializeObject(await clienttemperature);

listcontacts.DataSource = contacts;
listcontacts.DataBind();
Temparature.Text = temperature; 
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x