Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
565 views
Welcome To Ask or Share your Answers For Others

1 Answer

Scott Hanselman has the magic to use async with ASP.NET lifecycle events here

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...