0

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

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Stephen Cleary wrote an excellent article on this stuff, which you might find interesting.
0

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

1 Comment

Settings are correct.It is working when doing it synchronously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.