Entity framework 将SaveChangesAsync功能与非异步webapi一起使用
我用.net mvc4编写了一些webapi并使用EF6,现在我所有的api控制器都不是异步的,我想使用EF6的SaveChangesSync功能Entity framework 将SaveChangesAsync功能与非异步webapi一起使用,entity-framework,asp.net-mvc-4,asp.net-web-api,Entity Framework,Asp.net Mvc 4,Asp.net Web Api,我用.net mvc4编写了一些webapi并使用EF6,现在我所有的api控制器都不是异步的,我想使用EF6的SaveChangesSync功能 我的api看起来像 public HttpResponseMessage Post(#some argument) { ///so some computation and db operations without saving them // here i want to save all the db operations i h
我的api看起来像
public HttpResponseMessage Post(#some argument)
{
///so some computation and db operations without saving them
// here i want to save all the db operations i had done above
db.SaveChangesAsync();//Task 1
// again do some computation
// wait for operation(Task1) to get complelte
//do some computation
}
如何使用EF6 saveChangesSync()功能而不实际将每个api控制器更改为异步。返回一个,因此您可以在需要确保其完整性的时候调用它。您无需将方法更改为async
public HttpResponseMessage Post(#some argument)
{
Task saveTask = null;
///so some computation and db operations without saving them
bool shouldSave1 = doCalcs(onState);
if (shouldSave1) {
// here i want to save all the db operations i had done above
saveTask = db.SaveChangesAsync(); //Task 1
}
// again do some computation
if (shouldSave1) {
// wait for operation(Task1) to get complete
saveTask.Wait(); // this blocks until the task completes
}
//do some computation
}
脚注
这个答案只是告诉你如何做,假设你需要这样做。在这种特殊情况下(直接在操作中调用
savechangesync
),它将起作用。它没有讨论您是否应该这样做:在许多情况下,Wait
ing从异步方法返回的Task
将使ApiController
操作的请求上下文死锁。因此,以下代码不适用。请参见示例。感谢Andy的回复,实际上我是通过不使用“var”来实现的,因为在我的代码中,这是在某种条件下发生的,我想在该条件的范围之外等待。如果我理解正确,您只需要条件保存和条件等待?请参见上文。我们是否需要使用db.saveChangesSync().ConfigureAwait(false)?我们应该使用wait saveTask?@AnshulNigam,而不是wait等待-要得到正确的答案,你应该自己问这些问题。完整的答案非常有趣,因此可能值得询问,但简而言之,“否”(尝试一下,您会发现编译器错误很有趣)和“否”(除非您想使用async
,您在原始问题中说过必须避免),为什么不使用SaveChanges呢?