问题
Can a Page_Load()
method be async
? I ask as if I have declared as such
protected void Page_Load()
Everything loads as it should. If I have it declared as such
protected async void Page_Load()
the Page_Load()
breakpoint is not hit, nor does the catch()
block get hit.
Now I am trying to set my Page_Load()
method as async
in order to have 3 different stored procedures execute to completion before the page is fully rendered. If I do not have my Page_Load()
method as async
I get this compile error:
The await operator can only be used with an async method.
My code is as such.
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
}
回答1:
Scott Hanselman has the magic to use async with ASP.NET lifecycle events here
http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx
回答2:
No the ASP.NET design dose not call this method using any form of Task Await, so it cannot be Asnyc
来源:https://stackoverflow.com/questions/35899800/can-page-load-be-async