Page_Load() 可以异步吗

Mic*_*mon 9 c# asp.net asynchronous webforms

一个能Page_Load()方法是async?我问,好像我已经这样声明了

protected void Page_Load()
Run Code Online (Sandbox Code Playgroud)

一切都按其应有的方式加载。如果我有这样的声明

protected async void Page_Load()
Run Code Online (Sandbox Code Playgroud)

Page_Load()断点不会打,也没有对catch()块被击中。

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

await 运算符只能与异步方法一起使用。

我的代码是这样的。

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();
 }
Run Code Online (Sandbox Code Playgroud)

}

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
}
Run Code Online (Sandbox Code Playgroud)

n8w*_*wrl 15

Scott Hanselman 拥有在 ASP.NET 生命周期事件中使用异步的魔法

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