繁体   English   中英

异步等待MongoDB存储库的使用

[英]Async await usage for MongoDB repository

我有一个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);我收到以下警告blackListItemRepository.Insert(blackListItem);

因为不等待此调用,所以在调用完成之前将继续执行当前方法。 考虑将“ await”运算符应用于调用结果。

我是await和async关键字的新手,但不确定是否正确使用它们。 您对我的回购分类和用法有什么建议吗?

提前致谢,

调用异步方法时,应等待返回的任务,该任务只能在异步方法等中进行。等待任务可确保仅在操作完成后才继续执行,否则,操作及其后的代码将同时运行。

所以您的代码应该看起来像这样:

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 ,依此类推。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM