gpt4 book ai didi

entity-framework - Entity Framework 异步与 Task.FromResult

转载 作者:行者123 更新时间:2023-12-03 23:38:26 25 4
gpt4 key购买 nike

使用 Entity Framework 中 System.Data.Entity 提供的异步方法与使用 Task.FromResult 包装相同的非异步方法之间有什么区别吗?

例如:

    private Task<int> GetCountAsync()
{
return this._myDbContext.Set<MyEntity>().CountAsync();
}

    private Task<int> GetCountAsync()
{
return Task.FromResult(this._myDbContext.Set<MyEntity>().Count());
}

最佳答案

是的,它可以,因为如果 ADO 驱动程序使用 IOCP 线程池实现异步方法(它确实如此),将不会使用工作线程来等待操作,而是使用使用 I/O Completion Ports 的特殊等待机制。 ,以这种方式,当有很多争用像数据库查询那样对 IO 进行长时间运行的操作时,服务器应该能够最好地扩展。

检查一些你可以找到 google 的文章:

I/O Completion Ports

IOCP Thread Pooling in C#

Asynchronous Command Execution in ADO.NET 2.0

取自最后一个链接:

In previous versions of the .NET Framework it was possible to simulate non-blocking execution by using asynchronous delegates or the ThreadPool class; however, those solutions simply blocked another thread in the background, making them far from ideal for cases where it is important to avoid blocking threads...

ADO.NET/SqlClient asynchronous command execution support is based on true asynchronous network I/O under the covers (or non-blocking signaling in the case of shared memory).

...there are no blocked background threads waiting for a particular I/O operation to finish, and we use the overlapped I/O and the input/output completion ports facilities of the Windows 2000/XP/2003 operating systems to make it possible to use a single thread (or a few of them) to handle all the outstanding requests for a given process.

编辑:从评论移至此处以扩展有关异步存储库模式特定问题的答案:

我认为您应该公开您需要的那些异步方法,扩展通用存储库,避免在 EF 上耦合并避免任务包装,添加 CountAsync、AddSync、FindAsync 以及您还需要异步的所有类型的方法。

检查一下 ASYNCHRONOUS REPOSITORY PATTERN WITH ENTITY FRAMEWORK 6

存储库示例:

public interface IRepository<T> where T : class
{
Task<int> AddAsync(T t);
Task<int> RemoveAsync(T t);
Task<List<T>> GetAllAsync();
Task<int> UpdateAsync(T t);
Task<int> CountAsync();
Task<T> FindAsync(Expression<Func<T, bool>> match);
Task<List<T>> FindAllAsync(Expression<Func<T, bool>> match);
}

CountAsync 实现:

public async Task<int> CountAsync()
{
return await _dbContext.Set<T>().CountAsync();
}

直接从帖子中取出所有内容留在这里。

然后您还可以扩展您的通用存储库。

编辑:添加了一些有用的读物​​:

带有示例 Northwind ASP.NET MVC 5 应用程序的通用工作单元和存储库(轻量级流畅)框架:Repositories Framework

关于entity-framework - Entity Framework 异步与 Task.FromResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25201129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com