程序在调用 await 时退出 [英] Program exits upon calling await

查看:88
本文介绍了程序在调用 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.

因此,当您等待 printMessagemain 现在等待键输入时,控制将返回到您的主函数.当您按下键 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中的代码改为

InitializeMessageSystem().Wait();

等待直到 InitializeMessageSystem 完成,然后再等待密钥.

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

这篇关于程序在调用 await 时退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆