xkcd
xkcd

Reputation: 2590

Async await usage for MongoDB repository

I have a MongoDB repository class as you see below:

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();
    }
}

And I use this class as in the following code piece:

    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();
        }
    }

It works fine but I get the following warning for the line blackListItemRepository.Insert(blackListItem);

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

I'm new to await and async keywords and I'm not sure if I'm using them correctly. Do you have any suggestions for my repo class and my usage?

Thanks in advance,

Upvotes: 0

Views: 1596

Answers (1)

i3arnon
i3arnon

Reputation: 116568

When you call an async method you should await the returned task, which you can only do in an async method, etc. Awaiting the task makes sure you continue execution only after the operation completed, otherwise the operation and the code after it would run concurrently.

So your code should probably look like this:

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();
    }
}

Also, there's a naming convention for async methods which is to add an "Async" suffix to the name. So AddAsync instead of Add, InsertAsync instead of Insert and so forth.

Upvotes: 2

Related Questions