我正在使用Simple.Data和SQL Server,我有多个彼此独立的方法。在表单上,我有多个需要填充的下拉列表,我认为这些可以异步填充。我有一个返回实体列表的存储库。
在我的Asp.Net网站上,我逐个调用存储库中的方法并将它们绑定到下拉列表,这里是一个示例代码
private void Initialize()
{
LoadTechnologies();
LoadInstallationTypes();
LoadProvinces();
LoadYears();
}
private void LoadTechnologies()
{
ddlTechnologies.DataSource = _GizRepository.GetTechnologies();
ddlTechnologies.DataValueField = "Name";
ddlTechnologies.DataTextField = "Name";
ddlTechnologies.Items.Insert(0, new ListItem("All", "-1"));
ddlTechnologies.DataBind();
}
private void LoadInstallationTypes()
{
ddlInstallationType.DataSource = _GizRepository.GetInstallationTypes();
ddlInstallationType.DataValueField = "Type";
ddlInstallationType.DataTextField = "Type";
ddlInstallationType.Items.Insert(0, new ListItem("Any", "-1"));
ddlInstallationType.DataBind();
}
private void LoadProvinces()
{
ddlProvinces.DataSource = _GizRepository.GetProvinces();
ddlProvinces.DataValueField = "Name";
ddlProvinces.DataTextField = "Name";
ddlProvinces.Items.Insert(0, new ListItem("All", "-1"));
ddlProvinces.DataBind();
}
private void LoadYears()
{
ddlYearFrom.DataSource = _GizRepository.GetYears();
ddlYearFrom.DataValueField = "Year";
ddlYearFrom.DataTextField = "Year";
ddlYearFrom.DataBind();
ddlYearTo.DataSource = _GizRepository.GetYears();
ddlYearTo.DataValueField = "Year";
ddlYearTo.DataTextField = "Year";
ddlYearTo.DataBind();
}
您可以从上面的代码中看到,我所做的就是从存储库中获取一些列表并将它们绑定到下拉列表中。我想异步执行这些方法而不是同步,请指导它是如何完成的?
答案 0 :(得分:0)
使用async / await但不从每个例程返回任务。结果是他们同时运行所有等待他们自己的io然后在UI线程上完成。
private void Initialize()
{
LoadTechnologies();
LoadInstallationTypes();
LoadProvinces();
LoadYears();
}
// Note that LoadTechnologies will return as soon as it is
// called. The part after the await will be scheduled on
// the UI thread after the task completes with the data
private async Task LoadTechnologies()
{
ddlTechnologies.Datasource =
await Task.Run(()=>GizRepository.GetTechnologies());
ddlTechnologies.DataValueField = "Name";
ddlTechnologies.DataTextField = "Name";
ddlTechnologies.Items.Insert(0, new ListItem("All", "-1"));
ddlTechnologies.DataBind();
}
private async Task LoadInstallationTypes()
{
...
}
...
}
答案 1 :(得分:0)
目前无法使Simple.Data执行正确的异步数据库调用。工作从下周的第2版开始,第一个要添加的新功能是针对那些后端的正确异步操作 - 例如SQL Server - 其中ADO提供程序具有异步方法。