等待方法何时退出程序? [英] When will awaiting a method exit the program?

查看:94
本文介绍了等待方法何时退出程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读后续帖子,尤其是这一点:

I've been reading the following post, specifically this point:


在应用程序的入口点方法上,例如主要。当您等待尚未完成的实例时,执行将返回到方法的调用方。对于Main,它将从Main中退出,从而有效地终止程序。

On your application’s entry point method, e.g. Main. When you await an instance that’s not yet completed, execution returns to the caller of the method. In the case of Main, this would return out of Main, effectively ending the program.

我一直在尝试这样做,但我似乎无法退出。这是我的代码:

I've been trying to do that, but I can't seem to make it exit. Here's the code I have:

class Program
{
    // ending main!!!
    static async Task Main(string[] args)
    {
        Task<Task<string>> t = new Task<Task<string>>(async () =>
        {
            Console.WriteLine("Synchronous");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Synchronous");
                Console.WriteLine("Synchronous I is: " + i);
                await Task.Run(() => { Console.WriteLine("Asynchronous"); });
                await Task.Run(() => { for (int j = 0; j < 1000; j++) { Console.WriteLine( "Asynchronous, program should have exited by now?"); }});
            }
            return "ASD";
        });
        t.Start();
        await t;
    }
}

我在这里到底想念什么?敲行 await t; 或跟随 await中的线程,程序不应该退出Task.Run(()=> { Console.WriteLine( Asynchronous);});

What exactly am I missing here? Shouldn't the program exit upon hitting the line await t; or by following through the thread at await Task.Run(() => { Console.WriteLine("Asynchronous"); });?

这是Console应用程序的主要方法。

This is a Console application's main method.

推荐答案

您链接的文章来自2012年,该文章早于对Main()的异步支持,这就是为什么它在说什么似乎是错误的。

The article you linked is from 2012, which predates the addition of async support to Main(), which is why what it's talking about seems wrong.

对于当前实现,请考虑以下代码:

For the current implementation, consider the following code:

public static async Task Main()
{
    Console.WriteLine("Awaiting");
    await Task.Delay(2000);
    Console.WriteLine("Awaited");
}

这将由编译器进行如下转换(我使用了 JustDecompile 进行反编译):

This gets converted by the compiler as follows (I used "JustDecompile" to decompile this):

private static void <Main>()
{
    Program.Main().GetAwaiter().GetResult();
}

public static async Task Main()
{
    Console.WriteLine("Awaiting");
    await Task.Delay(2000);
    Console.WriteLine("Awaited");
}

现在您可以看到程序为何不退出了。

Now you can see why the program doesn't exit.

async Task Main() static void< Main>()等待从 async Task Main()返回的 Task 完成(通过访问 .GetResult())在程序退出之前。

The async Task Main() gets called from static void <Main>() which waits for the Task returned from async Task Main() to complete (by accessing .GetResult()) before the program exits.

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

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