为什么在通用存储库模式中某些返回Task的方法未标记为异步

我正在阅读一篇非常酷的文章,内容涉及使用以下链接https://blog.zhaytam.com/2019/03/14/generic-repository-pattern-csharp/创建通用Async存储库该接口将所有操作定义为任务,但是实现选择在某些方法上不使用async / await模式。我想进一步了解这一点,因此决定在此处发布。乍一看,客户端似乎可能不知道他们需要等待未标记为异步的方法,但我可能无法正确理解。任何人都可以评论为什么作者选择不对某些返回任务的方法而不是对其他方法使用异步吗?

public interface IAsyncRepository<T> where T : BaseEntity
{

    Task<T> GetById(int id);
    Task<T> FirstOrDefault(Expression<Func<T,bool>> predicate);

    Task Add(T entity);
    Task Update(T entity);
    Task Remove(T entity);

    Task<IEnumerable<T>> Getall();
    Task<IEnumerable<T>> GetWhere(Expression<Func<T,bool>> predicate);

    Task<int> CountAll();
    Task<int> CountWhere(Expression<Func<T,bool>> predicate);

}

public class EfRepository<T> : IAsyncRepository<T> where T : BaseEntity
{

    #region Fields

    protected DataDbContext Context;

    #endregion

    public EfRepository(DataDbContext context)
    {
        Context = context;
    }

    #region Public Methods

    public Task<T> GetById(int id) => Context.Set<T>().FindAsync(id);

    public Task<T> FirstOrDefault(Expression<Func<T,bool>> predicate)
        => Context.Set<T>().FirstOrDefaultAsync(predicate);

    public async Task Add(T entity)
    {
        // await Context.AddAsync(entity);
        await Context.Set<T>().AddAsync(entity);
        await Context.SaveChangesAsync();
    }

    public Task Update(T entity)
    {
        // In case AsnoTracking is used
        Context.Entry(entity).State = EntityState.Modified;
        return Context.SaveChangesAsync();
    }

    public Task Remove(T entity)
    {
        Context.Set<T>().Remove(entity);
        return Context.SaveChangesAsync();
    }

    public async Task<IEnumerable<T>> Getall()
    {
        return await Context.Set<T>().ToListAsync();
    }

    public async Task<IEnumerable<T>> GetWhere(Expression<Func<T,bool>> predicate)
    {
        return await Context.Set<T>().Where(predicate).ToListAsync();
    }

    public Task<int> CountAll() => Context.Set<T>().CountAsync();

    public Task<int> CountWhere(Expression<Func<T,bool>> predicate) 
        => Context.Set<T>().CountAsync(predicate);

    #endregion

}
jun576 回答:为什么在通用存储库模式中某些返回Task的方法未标记为异步

请注意,具有async的方法也具有await。在这些方法中,您等待执行以获取结果,而在没有await的方法中,您不在乎何时执行它们

,

我怀疑这是一个偶然的遗漏。

我很难看到等待一些基类方法而不是其他方法有什么好处。

,

仅使用提供的代码,除了public async Task Add(T entity)方法之外,“异步/等待”的使用似乎是完全随机的。

在所有情况下,您都可以将方法转换为async并在返回之前放置await,或者可以删除asyncawaits并返回Task

最后,无论是在编译代码方面还是在运行时行为方面(主要是性能),结果都是相同的

本文链接:https://www.f2er.com/3135631.html

大家都在问