我在EF6中看到了一個新特性,即異步方法。我找到一個例子。EF中這兩個異步調用有什麼區別?
這第一條路是正常通話,與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();
}
}
不過,我可以做以下(在大成是aprox的,我這樣做是由內存):
public async Task<Store> MyAsyncMethod(DbGeography location)
{
return await Task.Run(() => FindClosestStore());
}
我的意思是,我可以使用Task.Run調用第一種方法,那就是沒有異步,等待結果。目前,我用來調用異步的方法,不僅是EF。這也是一個異步調用,或者當我使用EF6異步方法時,真正的異步調用是什麼?
爲什麼在新版本的EF6中需要異步方法?只是爲了簡單?
async和await是語法糖,新的.Net 4.5,你可以通過任務與ContinueWith –