简体   繁体   中英

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?

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" %>

As of VS2022 you need to use

Page.RegisterAsyncTask(....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM