簡體   English   中英

異步方法即使被調用也不會被執行

[英]Async method doesn't get executed even when it gets called

我的工作流程:構造函數 -> 調用異步方法 1 -> 調用異步方法 2 -> 調用異步方法 3

構造函數:

public MyConstructor() {
    Method1();
}

方法一:

private async void Method1() {
    //do some stuff
    await Method2();
    //do some more stuff
}

方法二:

protected internal async Task Method2() {
    //do some stuff
    var x = await Method3("someParams");
    //do some more stuff
}

方法三:

public async Task<List<string>> Method3(string someParams) {
    Debug.WriteLine("I am here"); //Breakpoint doesn't get hit, no output "I am here"
}

是的,我知道,您可能想知道為什么我要使用這么多不同的異步方法......但是還有更多的東西在進行(但沒有任何影響問題的東西!)。 問題是, Debug.WriteLine("I am here"); 沒有得到命中,並且不會引發任何異常。

我做錯了什么?

簡而言之:是的,正如@fknx 在評論中提到的,問題是代碼異步執行並且沒有等待,因此應用程序在到達相關行之前退出。

您的示例中有一些不好的做法:

異步無效方法

創建這樣的東西不是一個好主意,因為你會失去對任務的跟蹤。 請始終將Task定義為返回值,它不會花費任何費用,並且會幫助您編寫正確的 API。

構造函數中的異步調用

這也不是一個好的設計,因為(正如你提到的)你不能在構造函數中等待這個方法,所以你只會啟動任務並釋放它。 請考慮使用異步初始化方法。

所以而不是這個:

public class MyCustomClass
{
    public MyCustomClass()
    {
        // BAD CODE, do not do this
        Method1();
    }

    private async Task Method1()
    {
        //do some stuff
        await Method2();
        //do some more stuff
    }
}

你可以這樣做:

class Program
{
    static void Main(string[] args)
    {
        var m = new MyCustomClass();

        m.InitializeAsync().Wait();

        Console.WriteLine("Before exit...");
    }
}

public class MyCustomClass
{
    public MyCustomClass()
    {
        // in a constructor you should not do anything async
    }

    public async Task InitializeAsync()
    {
        await Method1();
    }

    private async Task Method1()
    {
        //do some stuff
        await Method2();
        //do some more stuff
    }
}

這是絕對OK等待Main方法異步方法,或者更准確地說您的控制台應用程序只能一個等待(或為WaitAll,或者別的什么)方法的主要方法(和其他地方),如果你想創建一個真正的異步應用程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM