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

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

c# - Can Page_Load() Be Async

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

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

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...