为什么有些方法会返回未在通用存储库模式中标记为异步的Task,这是为什么?>

问题描述 投票:0回答:2

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

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

}

我正在阅读有关使用以下链接创建通用异步存储库的非常酷的文章https://blog.zhaytam.com/2019/03/14/generic-repository-pattern-csharp/接口定义了所有...

c# .net-core async-await ef-core-2.0
2个回答
1
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.