我定义了如下接口引出错误:
public interface INewsCategoryRepository { void CreateNewsCategory(NewsCategory newsCategory); }
然后用如下类实现了上述接口
public async void CreateNewsCategory(NewsCategory newsCategory)
{ var db = dbContext as NewsEFCoreContext; await db.Categories.AddAsync(newsCategory); }
于是问题出现了:
public class AddNewsCategoryUseCase { private readonly IRepository repository; private readonly INewsCategoryRepository newsCategoryRepository; public AddNewsCategoryUseCase(IRepository argRepository, INewsCategoryRepository argNewsCategoryRepository) { this.repository = argRepository; this.newsCategoryRepository = argNewsCategoryRepository; } /// <summary> /// 添加新的新闻 /// </summary> /// <param name="addNewsCategoryDto"></param> public async void AddNewsCategory(AddNewsCategoryDto addNewsCategoryDto) { NewsCategory newsCategory = addNewsCategoryDto.ToNewsCategory(); try { using (repository) { //newsCategoryRepository 是接口成员 其返回类型是void 没办法使用await--------------------------!!! await newsCategoryRepository.CreateNewsCategory(newsCategory); repository.Commit(); } } catch (Exception ex) { throw ex; } } }
截图如下:
正确的办法应该是:不能将接口方法定义为void 而应该定义为Task。(没有返回值就用Task,有返回值就用Task<T>)
public interface INewsCategoryRepository { Task CreateNewsCategory(NewsCategory newsCategory); }
实现类如下:
public async Task CreateNewsCategory(NewsCategory newsCategory) { var db = dbContext as NewsEFCoreContext; await db.Categories.AddAsync(newsCategory); }
调用这个方法如下:
public class AddNewsCategoryUseCase { private readonly IRepository repository; private readonly INewsCategoryRepository newsCategoryRepository; public AddNewsCategoryUseCase(IRepository argRepository, INewsCategoryRepository argNewsCategoryRepository) { this.repository = argRepository; this.newsCategoryRepository = argNewsCategoryRepository; } /// <summary> /// 添加新的新闻 /// </summary> /// <param name="addNewsCategoryDto"></param> public async Task AddNewsCategory(AddNewsCategoryDto addNewsCategoryDto) { NewsCategory newsCategory = addNewsCategoryDto.ToNewsCategory(); try { using (repository) { //没问题------------------!!! await newsCategoryRepository.CreateNewsCategory(newsCategory); repository.Commit(); } } catch (Exception ex) { throw ex; } } }
截图:
参考文章:异步编程中的最佳做法 https://msdn.microsoft.com/zh-cn/magazine/jj991977.aspx?f=255&MSPPError=-2147217396