Page_Load() 可以异步吗

Can Page_Load() Be Async

Page_Load() 方法可以是 async 吗?我问好像我已经这样声明了

protected void Page_Load()

一切正常加载。如果我这样声明

protected async void Page_Load()

Page_Load() 断点未命中,catch() 块也未命中。

现在我试图将我的 Page_Load() 方法设置为 async,以便在页面完全呈现之前执行 3 个不同的存储过程。如果我没有我的 Page_Load() 方法作为 async 我得到这个编译错误:

The await operator can only be used with an async method.

我的代码就是这样。

private DataSet ds1 = new DataSet();
private DataSet ds2 = new DataSet();
private DataSet ds3 = new DataSet();

protected async void Page_Load(object sender, EventArgs e)
{
 if (!IsPostBack)
 {
    var task1 = GetStoreInfo();
    var task2 = GetSalespersonInfo();
    var task3 = GetManagerInfo();
    await System.Threading.Tasks.Task.WhenAll(task1, task2, task3);
    PopulateAll();
 }

}

async System.Threading.Tasks.Task<DataSet> GetStoreInfo()
{
  ds1 = RunStoredProcedureToReturnThisData();
  return ds1;
}

async System.Threading.Tasks.Task<DataSet> GetSalespersonInfo()
{
  ds2 = RunStoredProcedureToReturnThisData();
  return ds2;
}

async System.Threading.Tasks.Task<DataSet> GetManagerInfo()
{
  ds3 = RunStoredProcedureToReturnThisData();
  return ds3;
}

protected void PopulateAll()
{
  //Bind the different returned datasets
}

否 ASP.NET 设计不使用任何形式的 Task Await 调用此方法,因此它不能是 Asnyc

Scott Hanselman 拥有使用异步与 ASP.NET 生命周期事件的魔力

http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx