我有一个MongoDB存储库类,如下所示:
public class MongoDbRepository<TEntity> : IRepository<TEntity> where TEntity : EntityBase
{
private IMongoClient client;
private IMongoDatabase database;
private IMongoCollection<TEntity> collection;
public MongoDbRepository()
{
client = new MongoClient();
database = client.GetDatabase("Test");
collection = database.GetCollection<TEntity>(typeof(TEntity).Name);
}
public async Task Insert(TEntity entity)
{
if (entity.Id == null)
{
entity.Id = Guid.NewGuid();
}
await collection.InsertOneAsync(entity);
}
public async Task Update(TEntity entity)
{
await collection.FindOneAndReplaceAsync(x => x.Id == entity.Id, entity, null);
}
public async Task Delete(TEntity entity)
{
await collection.DeleteOneAsync(x => x.Id == entity.Id);
}
public IList<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate)
{
return collection.Find(predicate, null).ToListAsync<TEntity>().Result;
}
public IList<TEntity> GetAll()
{
return collection.Find(new BsonDocument(), null).ToListAsync<TEntity>().Result;
}
public TEntity GetById(Guid id)
{
return collection.Find(x => x.Id == id, null).ToListAsync<TEntity>().Result.FirstOrDefault();
}
}
我使用此类,如下面的代码片段所示:
public void Add()
{
if (!string.IsNullOrEmpty(word))
{
BlackListItem blackListItem =
new BlackListItem()
{
Word = word,
CreatedAt = DateTime.Now
};
var blackListItemRepository = new MongoDbRepository<BlackListItem>();
blackListItemRepository.Insert(blackListItem);
Word = string.Empty;
GetBlackListItems();
}
}
它工作正常但我收到了blackListItemRepository.Insert(blackListItem);
由于未等待此调用,因此在完成调用之前会继续执行当前方法。考虑应用“等待”#39;运算符到调用的结果。
我是等待和异步关键字的新手,我不确定我是否正确使用它们。你对我的回购课程和我的用法有什么建议吗?
提前致谢,
答案 0 :(得分:2)
当你调用异步方法时,你应该等待返回的任务,你只能在异步方法中等等。等待任务确保你只在操作完成后继续执行,否则操作和后面的代码会同时运行。
所以你的代码应该是这样的:
public async Task AddAsync()
{
if (!string.IsNullOrEmpty(word))
{
BlackListItem blackListItem =
new BlackListItem()
{
Word = word,
CreatedAt = DateTime.Now
};
var blackListItemRepository = new MongoDbRepository<BlackListItem>();
await blackListItemRepository.InsertAsync(blackListItem);
Word = string.Empty;
GetBlackListItems();
}
}
此外,异步方法的命名约定是在名称中添加“Async”后缀。所以AddAsync
代替Add
,InsertAsync
代替Insert
等等。