0

I am trying to insert a document to the mongodb database using .NET. Since the async method in the driver is not familiar to me I find difficulties in doing this.

I am calling a non-async method for a button click.

private void Button_Click(object sender, RoutedEventArgs e)
{
    ConnectToMongo CM = new ConnectToMongo();
    CM.CallAyncMethod();
}

From the CallAyncMethod() I'm calling the async method

public void CallAyncMethod()
{
   try
   {
      InsertOneDocAsync().Wait();
   }
   catch (Exception ex)
   {
      Console.WriteLine($"There was an exception: {ex.ToString()}");
   }
}

Here is the async method that shoud insert a document to the database

public async Task InsertOneDocAsync()
    {
        _client = new MongoClient("mongodb://localhost:27017");
        _database = _client.GetDatabase("test");

        var document = new BsonDocument
        {
            { "_id", "0001" },
            { "address" , new BsonDocument
                {
                    { "street", "2 Avenue" },
                    { "zipcode", "10075" },
                    { "building", "1480" },
                    { "coord", new BsonArray { 73.9557413, 40.7720266 } }
                }
            },
            { "borough", "Manhattan" },
            { "cuisine", "Italian" },
            { "grades", new BsonArray
                {
                    new BsonDocument
                    {
                        { "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
                        { "grade", "A" },
                        { "score", 11 }
                    },
                    new BsonDocument
                    {
                        { "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
                        { "grade", "B" },
                        { "score", 17 }
                    }
                }
            },
            { "name", "Vella" },
            { "restaurant_id", "41704620" }
        };

        var collection = _database.GetCollection<BsonDocument>("restaurants");
        await collection.InsertOneAsync(document);
       // Console.WriteLine("hello");
    }

This does not insert a document to the database. This is what I get in the output console and it keeps on going

The thread 0x2424 has exited with code 0 (0x0).
The thread 0x155c has exited with code 0 (0x0).
The thread 0x26e0 has exited with code 0 (0x0).
The thread 0x131c has exited with code 0 (0x0).

When I commented all the code in the above method except // Console.WriteLine("hello"); it printed in the console. So, I guess the method has been called. Why is it not inserting the document?

How can I properly implement this?

Kabilesh
  • 1,000
  • 6
  • 22
  • 47
  • "driver"? Does not look like regular Windows device driver or anything like that... Is "driver" some MongoDB concept? – Alexei Levenkov Oct 11 '17 at 04:44
  • Side note: probably duplicate of https://stackoverflow.com/questions/13140523/await-vs-task-wait-deadlock – Alexei Levenkov Oct 11 '17 at 04:45
  • Yes. see https://docs.mongodb.com/ecosystem/drivers/csharp/ – Kabilesh Oct 11 '17 at 04:47
  • I see - read it wrong, I thought you are implementing driver of some sort. – Alexei Levenkov Oct 11 '17 at 04:50
  • I don't understand why those threads are displayed in the output window and what they are. – Kabilesh Oct 11 '17 at 04:52
  • 2
    Your code does insert the record for me (i.e. `InsertOneDocAsync` is fine), but as Alexei points out, it then deadlocks on the .Wait(). Change the button handler to `async void` and then [`await` instead of the blocking `Wait()`](https://stackoverflow.com/a/28601723/314291). You can drop the `CallAsyncMethod` wrapper altogether. If there is an existing record "_id", "0001" then this document will be overwritten, i.e. it will not insert multiple documents if you push the button more than once. – StuartLC Oct 11 '17 at 05:03
  • private async void Button_Click(object sender, RoutedEventArgs e) { ConnectToMongo CM = new ConnectToMongo(); await CM.InsertOneDocAsync(); } StuartLC are these the changes you mentioned? Still get the same problem? – Kabilesh Oct 11 '17 at 05:12
  • It inserts a document. Thanks. I have to look into why the threads keep on running. – Kabilesh Oct 11 '17 at 06:12
  • 1
    I wouldn't be too concerned about the [`thread has exited` messages](https://stackoverflow.com/q/12410548/314291) (they are Debug, not written to Console) - since threads all exit with code 0, it is healthy. It's likely just the threadpool trying to adjust to an optimum number of threads. – StuartLC Oct 12 '17 at 04:52

0 Answers0