programing

비동기 방식으로 코드를 디버깅할 수 없는 이유는 무엇입니까?

mailnote 2023. 5. 16. 22:52
반응형

비동기 방식으로 코드를 디버깅할 수 없는 이유는 무엇입니까?

사실 저는 MongoDB에 대해 더 배우기 위해 밤을 시작했지만, 전화를 끊고 있습니다.NET 대기/비동기화 항목.저는 MongoDB의 사이트에 나와 있는 코드를 구현하려고 합니다.프로그램을 컴파일할 수 있도록 약간 수정해야 했습니다.이제 콘솔 응용 프로그램에 다음이 있습니다.

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를 사용하지 않아야 합니다.

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
}

저는 비동기 개발을 잘 하지 못하고 비슷한 문제가 있었지만, 저는 비동기 방식을 시작하고 있었습니다.Main예:

Task.Run(async () => await GetDataAsync());

제 생각에 쓰레기 수집가는 익명의 방법을 더 이상 언급하지 않기 때문에 폐기한 것 같습니다.Fabien's 사용.Wait()프로그램과 디버그를 할 수 있게 해주었습니다.2017년 대비 Netcore 2.1을 사용하고 있습니다.

비동기 메서드의 Result 속성을 사용할 수 있습니다.

static void Main(string[] args)
{
    int x = GetData().Result;  

    // Result property will return you the out put datatype (not Task<datatype>)
    // Thread will be blocked here, to get you the data
}

private static async Task<int> GetData()
{
    // your code to get integer value return.

    return count;
}

언급URL : https://stackoverflow.com/questions/36733237/why-cant-i-debug-code-in-an-async-method

반응형