Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 871
Michael Mormon Avatar asked Mar 09 '16 18:03

Michael Mormon


People also ask

Is ASP Net Web API asynchronous?

Thanks to support for asynchronous programming in . NET 4.5 and C# 5, it is extremely easy to write asynchronous methods for an ASP.NET Web API service. Simply set the return type either to Task (if the synchronous version returns void) or to Task<T>, replacing T with the return type of the synchronous method.

How do you call async method in page load?

How can I call a async method on Page_Load ? If you change the method to static async Task instead of void, you can call it by using SendTweetWithSinglePicture("test", "path"). Wait() . Avoid async void unless you are using it for events.

How do you call a webservice method asynchronously in C#?

First, you tell the Web service to begin execution by calling the Begin method. The second step, calling the End method, completes the web service call and returns the response. To call a web service asynchronously, a client thread can use a WaitHandle.


1 Answers

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

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

like image 159
n8wrl Avatar answered Oct 17 '22 01:10

n8wrl