简体   繁体   English

C#如何调试异步

[英]C# How can I debug async

This question might me really easy, but I really don't understand how to do it. 这个问题我可能真的很容易,但是我真的不知道该怎么做。

I've created a class with multiple methods that call each other (first one does some logic and then calls the second one and so on) . 我创建了一个具有多个互相调用的方法的类(第一个执行一些逻辑,然后调用第二个,依此类推)。 All these methods are async due to await to POST and GET method from outside server. 由于等待外部服务器的POST和GET方法,所有这些方法都是异步的。

I want to debug my work, to see how it works on each stage and where have I gone wrong, but I don't know how. 我想调试我的工作,看它在每个阶段的工作方式以及我哪里出错了,但我不知道如何做。 I've tried calling the first function directly from the main function and add a break point, but got yield that "await" is missing, and after addi n "await" i'm getting yield that I need to make the method async, which contradict my purpose . 我尝试直接从主函数调用第一个函数并添加一个断点,但是却丢失了“ await”的产量,并且在添加“ await”之后,我需要使方法异步的产量,这与我的目的背道而驰。

What can I do ? 我能做什么 ?

    public static void Main(string[] args)
    {
        await LoadCampaignTempleteJSONAsync();
    }

All I want is to follow the process of LoadCampaignTempleteJSONAsync . 我想要做的就是遵循LoadCampaignTempleteJSONAsync的过程。

The simplest way to call async method from Main would be calling Result or GetAwaiter().GetResult() : 从Main调用异步方法的最简单方法是调用ResultGetAwaiter().GetResult()

public static void Main(string[] args)
{
    LoadCampaignTempleteJSONAsync().Result;
    LoadCampaignTempleteJSONAsync().GetAwaiter().GetResult();
}

Also, starting from C# 7.1 you can make Main async: 另外,从C#7.1开始,您可以使Main异步:

public static async Task Main(string[] args)
{
    await LoadCampaignTempleteJSONAsync();
}

Please try the following 请尝试以下

class Program
{
    static void Main(string[] args)
    {
        var p = new Program();
        p.Run();
    }

    private async void Run()
    {
        await LoadCampaignTempleteJSONAsync();
    }

    private static Task LoadCampaignTempleteJSONAsync()
    {
        //Put breakpoint here!
        throw new NotImplementedException();
    }
}

and put a breakpoint inside the LoadCampaignTempleteJSONAsync() this will hit the breakpoint 并在LoadCampaignTempleteJSONAsync()内放置一个断点,它将命中该断点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM