【问题标题】:what is the difference between this two async call in EF?EF中这两个异步调用有什么区别?
【发布时间】: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


【解决方案1】:

这里的区别在于代码的等待方式。

在这段代码中:

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();
    }
}

EF 将对数据库发出查询,然后返回。

一旦结果返回,任务将完成,等待块将继续执行。

也就是说,.NET 本身没有等待响应的线程。 有(希望)来自 db 驱动程序的较低级别的回调,当结果到达时通知 .NET。

(这至少是其他异步 IO 在 .NET 中的工作方式,我假设 ADO.NET 异步也是如此)

另一种情况:

public async Task<Store> MyAsyncMethod(DbGeography location)
{
     return await Task.Run(()=> FindClosestStore());
}

会有一个线程等待数据库的响应。也就是说,您将拥有阻塞 IO,但它会通过您的 task.run 技巧对消费者隐藏。

对于消费者来说,这两种情况的行为相同,不同之处在于您在上一个示例中占用了资源。

【讨论】:

  • 我认为使用 async/await 可以避免使用新线程。有时是创建的,有时不是(取决于情况)。实际上,在 WCF 中,它使用 async/await 模式在处理请求时释放资源。使用 EF 是否会以相同的方式工作,在请求执行时释放资源?
  • 在最后一个代码示例中,会有一个阻塞线程,因为它使用了非异步 EF 方法。即使您将该调用包装在 async/await 块中。那是。 “FindClosestStore()”会在后台阻塞线程
  • 当使用 async/await 时,这不会发生在 WCF 中吗?有什么方法可以在 EF5 中使用异步?
猜你喜欢
  • 2019-01-31
  • 1970-01-01
  • 2018-01-14
  • 2016-08-05
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多