我实际上是在晚上开始尝试了解有关 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()
方法中放置的任何断点一样。这段代码是不是因为程序退出而没有运行?有人可以向我解释发生了什么吗?
最佳答案
因为您没有 await
执行您的 GetDataAsync
方法。当到达第一个 await
时,线程将返回给调用者。由于您没有等待任务完成,因此您的控制台应用程序将退出并且您的断点未到达。您还需要更新 GetDataAsync
方法以返回 Task
而不是 void。你不能等待无效。你应该 avoid using async void除了事件处理程序之外的任何东西。
protected static IMongoClient _client;
protected static IMongoDatabase _database;
static void Main(string[] args)
{
_client = new MongoClient();
_database = _client.GetDatabase("test");
GetDataAsync().Wait();
// Will block the calling thread but you don't have any other solution in a console application
}
private static async Task 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
}
关于c# - 为什么我不能在异步方法中调试代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36733237/