john.kernel
john.kernel

Reputation: 360

Insert entity to MongoDb async not working

could somebody tell me why this code not working ? It compiles, it runs but the Mongo database is still empty. It is working when doing it synchronously.

class Program
{
    static void Main(string[] args)
    {
        var client = new MongoClient();
        var db = client.GetDatabase("Mongo");
        var collection = db.GetCollection<User>("Users");

        User user = new User("Denis", "Chang", "China", 21);
        AddUserAsync(user, collection);
    }

    static async void AddUserAsync(User user, IMongoCollection<User> collection)
    {
        await collection.InsertOneAsync(user);
    }
}

Upvotes: 0

Views: 851

Answers (2)

Kirk Larkin
Kirk Larkin

Reputation: 93053

You're not waiting for AddUserAsync to complete. In order to do so, you have a couple of options:

  1. Use AddUserAsync(user, collection).GetAwaiter().GetResult(), which will block until the asynchronous function completes.
  2. If you're using C# 7.1, you can use an async Main, like so:

    static async Task Main()
    {
        ...
        await AddUserAsync(user, collection);
    }
    

In order for either of these approaches to work, you'll also need to update your AddUserAsync function to return a Task, simply by changing the signature:

static async Task AddUserAsync(User user, IMongoCollection<User> collection)

Upvotes: 2

smolchanovsky
smolchanovsky

Reputation: 1863

The method is asynchronous but you do not wait for the completion of the operation. Try this

static async Task AddUserAsync(User user, IMongoCollection<User> collection)
{
    await collection.InsertOneAsync(user);
}

and then

AddUserAsync(user, collection).Wait();

Upvotes: 0

Related Questions