程序在等待时退出 [英] Program exits upon calling await
问题描述
我有一个while
循环,该循环应重复执行该程序,直到满足特定条件为止.在此循环中,我调用了async
函数,该函数为我打印出一条消息.这是(简写)代码:
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 message for me. Here is the (cut-short) code:
private void InitializeMessageSystem ( )
{
do
{
// Do stuff
await printMessage ("Hello World!");
Console.ReadKey();
} while (condition != true)
}
这里是函数PrintMessage()
:
private static async Task PrintMessage (string message, int spd = 1)
{
int delay = 50 / spd;
string[] words = message.Split(' ');
int index = 1;
for (int word = 0; word < words.Length; word++)
{
char[] current = words[word].ToCharArray();
if (index + current.Length > Console.WindowWidth)
{
Console.WriteLine();
index = 1;
}
for (int c = 0; c < current.Length; c++)
{
Console.Write(current[c]);
await Task.Delay(delay);
}
Console.Write(" ");
}
}
编辑:这是来自主要功能的调用:
Edit: Here's the call from the main function:
static void Main (string[] args)
{
InitializeMessageSystem();
Console.ReadKey();
}
问题
为什么在功能尚未完成时按一个键,为什么我的程序会退出?我以为程序会等到Console.ReadKey()
直到功能PrintMessage()
完成?
Why does my program exit, when I press a key while the function is not yet completed? I thought the program would wait for the Console.ReadKey()
until the function PrintMessage()
is completed?
推荐答案
您的问题是await
将程序的控制流返回给函数的调用者.通常,等待的异步任务完成后,将继续执行.
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.
因此,当您等待printMessage
时,控制权将返回到您的主要功能,并且main
现在等待键输入.按下键时,main
返回操作系统,并且您的进程(包括所有异步任务)终止.
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.
将您的InitializeMessageSystem
更改为
private async Task InitializeMessageSystem ( )
,然后将main
中的代码更改为
and change the code in main
to
InitializeMessageSystem().Wait();
要等到InitializeMessageSystem
完全完成后再等待键.
to wait until InitializeMessageSystem
finishes completely before waiting for the key.
这篇关于程序在等待时退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!