前面的示例代码使用了一个同步服务。如果使用Entity Framework Core(EF Core)和存储库,可以使用同步或异步的方法。EF Core支持两者。然而,许多技术(例如使用HttpClient类调用其他服务)只提供了异步的方法。这可能会导致一个异步服务,如Async文件夹中的项目BooksServicesSample所示。
在异步项目中,IBookChaptersService已经改为异步的版本。这个接口定义为通过服务访问异步方法,如网络或数据库客户端。所有的方法都返回Task:
public interface IBookChaptersService
{
Task AddAsync(BookChapter bookChapter);
Task AddRangeAsync(IEnumerable<BookChapter> chanters);
Task<IEnumerable<BookChapter>> GetAllAsync();
Task<BookChapter> FindAsync(Guid id);
Task<BookChapter> RemoveAsync(Guid id);
Task UpdateAsync(BookChapter bookChapter);
}
类BookChaptersService实现了异步方法。读写字典时,不需要异步功能,所以返回的Task使用FromResult方法创建:
public class BookChaptersService:IBookChaptersService
{
private readonly ConcurrentDictionary<Guid