【发布时间】:2014-06-26 01:44:30
【问题描述】:
我在控制器中有 asp.net mvc 任务:
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));
}
方法UpdateContactAsync 看起来像这样:
public async Task<int> UpdateContactAsync(ContactModel update)
{
Contact c = await this.Db.GetContactAsync(id);
OtherContact oc = await this.Db.GetOtherContactAsync(id);
// do stuff with contact and other contact
// finally
return await this.accessor.Db.SaveChangesAsync();
}
上面的代码运行没有任何问题。
但我尝试进行一些调整以运行这两个任务,并在运行后等待它们并将代码更改为以下:
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 的情况来看,只有第一个任务正在运行。
【问题讨论】:
-
如果您的存储库使用 EntityFramework,请注意不支持从多个线程同时访问相同的 DbContext。但是,就像@Servy 提到的那样,您需要告诉我们什么不起作用。否则我们只能猜测。 :)
-
好吧,我问错了。我宁愿问第一个和第二个之间的区别是什么导致代码中永远无法达到 SaveAsync。
标签: c# asp.net-mvc async-await