【发布时间】:2016-04-20 03:22:07
【问题描述】:
我实际上是在晚上开始尝试了解有关 MongoDB 的更多信息,但我被挂断了,而且 .NET 等待/异步的东西。我正在尝试实现 MongoDB 的site 上显示的代码。我不得不稍微修改一下,这样我才能编译我的程序。我现在在我的控制台应用程序中有以下内容:
protected static IMongoClient _client;
protected static IMongoDatabase _database;
static void Main(string[] args)
{
_client = new MongoClient();
_database = _client.GetDatabase("test");
GetDataAsync();
}
private static async void GetDataAsync() //method added by me.
{
int x = await GetData();
}
private static async Task<int> GetData()
{
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = new BsonDocument();
var count = 0;
Func<int> task = () => count; //added by me.
var result = new Task<int>(task); //added by me.
using (var cursor = await collection.FindAsync(filter)) //Debugger immediately exits here, goes back to main() and then terminates.
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var document in batch)
{
// process document
count++;
}
}
}
return count; //added by me
}
当我运行应用程序时,调试器将调用我的GetDataAsync() 方法,该方法又调用GetData() 方法。它到达using (var cursor = await collection.FindAsync(filter)) 行,然后立即返回以完成main() 方法。
我在该行下方放置的任何断点都将被忽略,就像我在 GetDataAsync() 方法中放置的任何断点一样。这段代码是不是因为程序退出而没有运行?有人可以向我解释发生了什么吗?
【问题讨论】:
-
Visual Studio 更新后,处理调试模式变得更加一致。如果您还没有,最好尽快更新它。而这篇文章可以帮助我希望devblogs.microsoft.com/visualstudio/…
标签: c# mongodb asynchronous