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 ASP.net 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?

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

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("http://www.example.com");

    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.


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