在c#.NET驱动程序2.0中从非异步调用异步方法

时间:2017-10-11 04:39:08

标签: c# .net mongodb asynchronous

我正在尝试使用.NET将文档插入mongodb数据库。由于我不熟悉驱动程序中的异步方法,我发现这样做有困难。

我正在为按钮点击调用非异步方法。

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

来自CallAyncMethod()我正在调用异步方法

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

这是将文档插入数据库的异步方法

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

这不会将文档插入数据库。这是我在输出控制台中得到的,它一直在继续

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).

当我评论上述方法中的所有代码,除了// Console.WriteLine(“hello”);它打印在控制台中。所以,我猜这个方法已被调用。为什么不插入文档?

如何正确实施?

0 个答案:

没有答案