Program exits upon calling await

后端 未结 3 667
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 18:21

I have a while-loop that should repeat the program until a certain condition is met. Inside this loop I call an async function, which prints out a

3条回答
  •  被撕碎了的回忆
    2020-12-03 18:53

    Your problem is that await returns the control flow of the program to the caller of the function. Normally execution is continued at that point when the asynchronous task you await finishes.

    So control is returned to your main function as you wait for printMessage and main now waits for a key input. As you hit the key main returns to the OS and your process (including all asynchronous tasks) terminates.

    Change your InitializeMessageSystem to

    private async Task InitializeMessageSystem ( )  
    

    and change the code in main to

    InitializeMessageSystem().Wait();
    

    to wait until InitializeMessageSystem finishes completely before waiting for the key.

提交回复
热议问题