Dozer Dozer - 4 years ago 160
ASP.NET (C#) Question

How to use async/await to achieve asynchronous page in 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(""));

But how to use it in ASP.NET WebForms?

Answer Source

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("");

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download