简体   繁体   English

ASP.Net:在 Page_Load 中调用异步方法

[英]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. 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.现在我需要在 ASP.net page_load 事件中运行这个 post 方法。 I have seen similar examples here, however what I need is to get my return object from my async method.我在这里看到了类似的例子,但是我需要的是从我的异步方法中得到我的返回 object。

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但是我有两个问题,首先 PageAsyncTask 不接受我的 Send 方法作为有效的 Task 类型,我想这是因为我的方法返回 Task 类型的 Task 所以它抱怨它不能将 Task 转换为 System.Func

Also how can I get my object of ReturnedResults out of this once it is successfully executed?另外,一旦成功执行,我怎样才能从中获得 ReturnedResults 的 object?

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. 仅仅因为您无法等待PageAsyncTask的结果并不意味着任务本身无法启动您可以等待的更多功能。 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从 VS2022 开始,您需要使用

Page.RegisterAsyncTask(....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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