C# 关于async/await,我缺少什么
我在控制器中有asp.net mvc任务:C# 关于async/await,我缺少什么,c#,asp.net-mvc,async-await,C#,Asp.net Mvc,Async Await,我在控制器中有asp.net mvc任务: public async Task<ActionResult> ContactUpdate(ContactViewModel update) { if (update != null && this.ModelState.IsValid) { await new ContactRepository(this).Upd
public async Task<ActionResult> ContactUpdate(ContactViewModel update)
{
if (update != null && this.ModelState.IsValid)
{
await new ContactRepository(this).UpdateContactAsync(update);
}
return this.Json(new FormResult(this.ModelState));
}
以上代码工作正常,没有任何问题
但我尝试进行一些调整以运行这两个任务,并在运行后等待它们,并将代码更改为:
public async Task<int> UpdateContactAsync(ContactModel update)
{
var task1 = this.Db.GetContactAsync(id);
var task2 = this.Db.GetOtherContactAsync(id);
Contact c = await task1;
OtherContact oc = await task2;
// do stuff with contact and other contact
// finally
return await this.accessor.Db.SaveChangesAsync();
}
这段代码并没有像我预期的那样工作:第二段代码永远不会到达第二个任务等待并保存。根据我在DB Profiler上看到的情况,只有第一个任务正在运行。实体框架每次只允许每个DbContext执行一个异步请求。如果存储库使用的是EntityFramework,请注意,不支持从多个线程并发访问同一个DbContext。但是,就像@Servy提到的,你需要告诉我们什么不起作用。否则我们只能猜测好吧,我问错问题了。我更应该问,第一个和第二个之间的差异是什么,导致SaveAsync在代码中永远无法实现。
public async Task<int> UpdateContactAsync(ContactModel update)
{
var task1 = this.Db.GetContactAsync(id);
var task2 = this.Db.GetOtherContactAsync(id);
Contact c = await task1;
OtherContact oc = await task2;
// do stuff with contact and other contact
// finally
return await this.accessor.Db.SaveChangesAsync();
}