【发布时间】:2012-11-12 10:04:14
【问题描述】:
我在 EF6 中看到了一个新功能,即异步方法。我找到了一个例子。
第一种方式是普通调用,以EF5为例:
public Store FindClosestStore(DbGeography location)
{
using (var context = new StoreContext())
{
return (from s in context.Stores
orderby s.Location.Distance(location)
select s).First();
}
}
还有新的调用,在 EF6 中使用异步方法。
public async Task<Store> FindClosestStore(DbGeography location)
{
using (var context = new StoreContext())
{
return await (from s in context.Stores
orderby s.Location.Distance(location)
select s).FirstAsync();
}
}
但是,我可以执行以下操作(语法是近似的,我是靠记忆做的):
public async Task<Store> MyAsyncMethod(DbGeography location)
{
return await Task.Run(() => FindClosestStore());
}
我的意思是,我可以使用 Task.Run 调用第一个方法,即非异步,以等待结果。目前,是我用来调用异步任何方法的方式,而不仅仅是 EF。这也是异步调用还是真正的异步调用是在我使用 EF6 异步方法时?
为什么在新版本的 EF6 中需要异步方法?只是为了简单?
【问题讨论】:
-
async 和 await 是语法糖,在 .Net 4.5 中新增,您可以通过 Task 和 ContinueWith 来做同样的事情
标签: c# entity-framework asynchronous async-await