[英]Why do some async methods require a return type of Task, and others don't
[英]Why are some methods that return a Task not marked as Async in generic repository pattern
我正在閱讀一篇關於使用以下鏈接創建通用異步存儲庫的非常酷的文章https://blog.zhaytam.com/2019/03/14/generic-repository-pattern-csharp/該接口將所有操作定義為任務,但實現選擇在一些方法上不使用 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
}
請注意,這些方法有async
也有await
。 在那些方法中,您等待執行以獲取結果,同時在那些沒有await
的方法中,您不在乎它們何時執行
我懷疑這是一個意外遺漏。
我很難看到等待一些基本 class 方法而不是其他方法有什么好處。
僅使用提供的代碼,除了public async Task Add(T entity)
方法外,“異步/等待”的使用似乎是完全隨機的。
在所有情況下,您都可以將方法轉換為async
並在返回之前放置一個await
,或者您可以刪除async
和awaits
並返回Task
。
最后,結果是相同的,無論是編譯代碼還是運行時的行為(主要是性能)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.