ASP.Net: Call an async method in Page_Load

I have this API client which has a send method used to post my object to a Web API service and return an object of type ReturnedResults.
Now I need to run this post method in an page_load event.
I have seen similar examples here, however what I need is to get my return object from my async method.

I know that I am supposed to use

PageAsyncTask t = new PageAsyncTask(APIService.Send("test"));

However I have two problems, first PageAsyncTask doesn’t accept my Send method as a valid Task type, I guess that’s because my method returns a Task of Task type so it complains that it can’t convert Task to System.Func

Also how can I get my object of ReturnedResults out of this once it is successfully executed?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Just because you can’t await the result of a PageAsyncTask doesn’t mean that the task itself can’t kick off more functions that you can then await. You can take advantage of this to have an async page load.

public void Page_Load(object sender, EventArgs e)
    RegisterAsyncTask(new PageAsyncTask(PageLoadAsync));
public async Task PageLoadAsync()
    //perform your actions here, including calling async methods and awaiting their results

    Task<string> downloadTask = new WebClient().DownloadStringTaskAsync("");

    TextBox1.Title = "We can do some actions while waiting for the task to complete";

    TextBox2.Title = await downloadTask;

Make sure your page is marked as async.

<%@ Page Language="C#" CodeBehind="Default.aspx.cs" Inherits="Default" Async="true" %>

Keep in mind that the above code is slightly misleading. ASP.NET Web Forms is still based on the HTTP request/response model. It can’t actually update a textbox’s title on the client side while waiting for some file to download. Instead, it updates the textbox’s title in the HTTP response, and once all server side processing is done (including your asynchronous tasks) it will then send the response to the client, at which point they’ll see the updated textbox’s title.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

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

Leave a Reply