Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

c# - Program exits upon calling await

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)
}

And here the function 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();
}

Question

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...