使用SaveChangesAsync功能与非异步的WebAPI [英] Using SaveChangesAsync feature with non async webapi
问题描述
我有一定的WebAPI .NET编写mvc4和使用EF6,现在我所有的API控制器不是异步的,我想用EF6结果的SaveChangesAsync特点
I have some webapi written in .net mvc4 and using EF6 , now all my api controllers are not async , and i wanted to use SaveChangesAsync feature of EF6
我的API看起来类似结果
My api looks something like
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 SaveChangesAsync()功能,而不用真正改变我的每个API控制器的异步到
How can i make use of EF6 SaveChangesAsync() feature without actually changing each of my api controller to async.
推荐答案
的 SaveChangesAsync
返回的 任务
,所以你可以叫的 任务。等待()
你需要确保它是完整的地步。你并不需要改变异步的方法,为了做到这一点。
SaveChangesAsync
returns a Task
, so you can just call Task.Wait()
at the point you need to make sure it's complete. You don't need to change the method to async
in order to do this.
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
}
脚注
这个答案只能说明你是如何做到这一点假设你需要。在这种特殊情况下(调用 SaveChangesAsync
直接在操作中),它会正常工作。它不讨论,如果你应该做的是:有很多情况下等待
ING在工作
从异步返回方法将死锁 ApiController
操作的请求上下文。因此下面的code是不恰当的。请参见斯蒂芬·克利里:不要阻止异步code 一个例子。
Footnote
This answer only shows you how to do this assuming you need to. In this particular situation (calling SaveChangesAsync
directly within the action) it will work. It does not discuss if you should do it: there are many situations where Wait
ing on the Task
returned from an async method will deadlock the ApiController
action's request context. The code below would therefore not be appropriate. See Stephen Cleary: Don't Block on Async Code for an example.
这篇关于使用SaveChangesAsync功能与非异步的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!