Why does async / await not work in my ASP.NET 5 console application?

I tried this simple ASP.net 5 Console application on both Windows (.NET 4.5.1) and Linux (Mono 4.0.1), both times with the same result.

Note. I called it the ASP.net 5 console application because this is what was called in Visual Studio before RC. Now it is called a console application (Package), but it still uses DNX from https://github.com/aspnet/dnx :)

My Program.cs:

using System;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public class Program
    {
        public async void Main(String[] args)
        {
            #if DNX451
            AppDomain.CurrentDomain.UnhandledException += 
                (s, e) => Console.WriteLine(e);
            #endif

            try
            {
                await Task.Delay(1000);
                Console.WriteLine("After Task.Delay");
            }
            finally
            {
                Console.WriteLine("Inside Finally");
            }
        }
    }
}

My project.json:

{
    "version": "1.0.0-*",
    "dependencies": {},
    "commands": {
        "ConsoleApplication": "ConsoleApplication"
    },
    "frameworks": {
        "dnx451": {}
    }
}

When working with 1.0.0-beta4 CLRor, the 1.0.0-beta5-11904 CLRcommand dnx . ConsoleApplicationdisplays nothing. The program exits with status 0 as soon as it encounters Task.Delay. Even the finally block is never executed.

.NET Core 5.0, dnu restore , , . , ...

- async/await DNX? ?

+4
1

( ) 'async' CoreCLR?, , - , :

public static int Execute(string[] args)
{
    // If we're a console host then print exceptions to stderr
    var printExceptionsToStdError = Environment
                                    .GetEnvironmentVariable
                                     (EnvironmentNames.ConsoleHost) == "1";

    try
    {
        return ExecuteAsync(args).GetAwaiter().GetResult();
    }
    catch (Exception ex)
    {
        if (printExceptionsToStdError)
        {
            PrintErrors(ex);
            return 1;
        }

        throw;
    }
}

, Task, ContinueWith, :

if (result is Task)
{
    return ((Task)result).ContinueWith(t =>
    {
        return 0;
    });
}

async void, Execute, " ". . , , Task, :

public async Task Main(String[] args)
{
    #if DNX451
    AppDomain.CurrentDomain.UnhandledException += 
        (s, e) => Console.WriteLine(e);
    #endif

    try
    {
        await Task.Delay(1000);
        Console.WriteLine("After Task.Delay");
    }
    finally
    {
        Console.WriteLine("Inside Finally");
    }
}
+11

All Articles