问题描述
Page_Load()
方法可以async
吗?我问,好像我已经声明过
protected void Page_Load()
一切正常加载.如果我把它声明为这样
protected async void Page_Load()
Page_Load()
断点没有命中,catch()
块也没有命中.
现在我试图将我的 Page_Load()
方法设置为 async
以便在页面完全呈现之前执行 3 个不同的存储过程.如果我没有将 Page_Load()
方法作为 async
我得到这个编译错误:
await 运算符只能与异步方法一起使用.
我的代码就是这样.
private DataSet ds1 = new DataSet();私有数据集 ds2 = 新数据集();私有数据集 ds3 = 新数据集();protected async void Page_Load(object sender, EventArgs e){如果 (!IsPostBack){var task1 = GetStoreInfo();var task2 = GetSalespersonInfo();var task3 = GetManagerInfo();等待 System.Threading.Tasks.Task.WhenAll(task1, task2, task3);填充全部();}
}
async System.Threading.Tasks.Task获取商店信息(){ds1 = RunStoredProcedureToReturnThisData();返回 ds1;}异步 System.Threading.Tasks.Task获取销售人员信息(){ds2 = RunStoredProcedureToReturnThisData();返回 ds2;}异步 System.Threading.Tasks.Task获取经理信息(){ds3 = RunStoredProcedureToReturnThisData();返回 ds3;}受保护的无效 PopulateAll(){//绑定不同的返回数据集}
Scott Hanselman 拥有在 ASP.NET 生命周期事件中使用异步的魔法
http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportant.aspx.aspx/p>
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
}
Scott Hanselman has the magic to use async with ASP.NET lifecycle events here
http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx
这篇关于Page_Load() 可以异步吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!