我将剃刀页面的
OnGet
切换为异步,我注意到我的一些控件将不再可靠地加载。
我的页面上有一个剑道多重选择,一旦我切换到异步,它仅在大约 50% 的时间内加载选项列表。不包含选项列表的控件似乎可以正常加载。我切换回同步,一切都再次可靠地加载。从数据库获取数据来填充页面时,async/await 是否不适合使用?
这是我的
OnGet
的异步版本:
public async void OnGet(int securityGroupId)
{
if (securityGroupId == -1)
{
SecurityGroup = new SecurityGroup();
SecurityGroup.IsActive = true;
}
else
{
SecurityGroup = await DL.GetEntityByIdAsync<SecurityGroup, int>(securityGroupId);
}
RoleList = await DL.GetLookupListAsync<Role>();
RoleList = RoleList.OrderBy(r => r.Text).ToList();
}
这是同步版本:
public void OnGet(int securityGroupId)
{
if (securityGroupId == -1)
{
SecurityGroup = new SecurityGroup();
SecurityGroup.IsActive = true;
}
else
{
SecurityGroup = DL.GetEntityById<SecurityGroup, int>(securityGroupId);
}
RoleList = DL.GetLookupList<Role>().OrderBy(r => r.Text).ToList();
}
RoleList
是:public List<DDL> RoleList { get; set; }
DDL
是一个包含字符串Id和字符串Text的类;
这是
GetEntityById
的异步版本:
public async Task<TEntity> GetEntityByIdAsync<TEntity, TId>(TId id) where TEntity : class, IIdentifiable<TId>, new()
where TId : IEquatable<TId>
{
var entity = new TEntity();
try
{
entity = await db.Set<TEntity>().FirstOrDefaultAsync(t => t.Id.Equals(id));
}
catch (Exception ex)
{
throw ex;
}
return entity;
}
这是同步版本:
public TEntity GetEntityById<TEntity, TId>(TId id) where TEntity : class, IIdentifiable<TId>, new()
where TId : IEquatable<TId>
{
var entity = new TEntity();
try
{
entity = db.Set<TEntity>().FirstOrDefault(t => t.Id.Equals(id));
}
catch (Exception ex)
{
throw ex;
}
return entity;
}
这是
GetLookupList
的异步版本:
public async Task<List<DDL>> GetLookupListAsync<TEntity>() where TEntity : class, IDDLable
{
List<DDL> ddl = new List<DDL>();
try
{
ddl = await db.Set<TEntity>().Select(lu => new DDL { Id = lu.DDLId, Text = lu.DDLText }).ToListAsync();
}
catch (Exception ex)
{
throw ex;
}
return ddl;
}
这是同步版本:
public List<DDL> GetLookupList<T>() where T : class, IDDLable
{
List<DDL> ddl = new List<DDL>();
try
{
ddl = db.Set<T>().Select(lu => new DDL { Id = lu.DDLId, Text = lu.DDLText }).ToList();
}
catch (Exception ex)
{
throw ex;
}
return ddl;
}
多选定义为:
@(Html.Kendo().MultiSelectFor(m => m.SelectedRoles)
.DataValueField("Id")
.DataTextField("Text")
.AutoClose(false)
.Placeholder("Select Role(s)...")
.BindTo(Model.RoleList))
将 OnGet 的返回类型从
void
更改为 Task
解决了该问题。 Async
后缀没有任何效果,我相信这只是命名约定的问题。
该函数现在显示为:
public async Task OnGetAsync(int securityGroupId)
{
if (securityGroupId == -1)
{
SecurityGroup = new SecurityGroup();
SecurityGroup.IsActive = true;
}
else
{
SecurityGroup = await DL.GetEntityByIdAsync<SecurityGroup, int>(securityGroupId);
SelectedRoles = SecurityGroup.RoleIdList;
}
RoleList = await DL.GetLookupListAsync<Role>();
RoleList = RoleList.OrderBy(r => r.Text).ToList();
}