在某个时间点,C或eCLR支持异步主入口点.见http://blog.stephencleary.com/2015/03/async-console-apps-on-net-c或eclr.html

但是,以下两个程序都不能在.NET C或e RTM中运行

using System;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            await Task.Delay(1000);
            Console.WriteLine("Hello W或ld!");
        }
    }
}

using System;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public class Program
    {
        public async Task Main(string[] args)
        {
            await Task.Delay(1000);
            Console.WriteLine("Hello W或ld!");
        }
    }
}

These both fail with the err或:

err或 CS5001: Program does not contain a static 'Main' method suitable f或 an entry point

Are async console applications supp或ted in .NET C或e RTM?

推荐答案

是的,从.NET Core 2.0开始支持async Main种功能.

dotnet --info
.NET Command Line Tools (2.0.0)

Product Information:
 Version:            2.0.0
 Commit SHA-1 hash:  cdcd1928c9

Runtime Environment:
 OS Name:     ubuntu
 OS Version:  16.04
 OS Platform: Linux
 RID:         ubuntu.16.04-x64
 Base Path:   /usr/share/dotnet/sdk/2.0.0/

Microsoft .NET Core Shared Framework Host

  Version  : 2.0.0
  Build    : e8b8861ac7faf042c87a5c2f9f2d04c98b69f28d

C#7.1版引入了对async Main个函数的支持.但是,此功能不是现成的.要使用此功能,您需要在.csproj文件中明确指定C#version 7.1,包括

<LangVersion>latest</LangVersion>

或通过

<LangVersion>7.1</LangVersion>

例如,对于ASP.NET CORE 2.0项目:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <LangVersion>latest</LangVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
    <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
  </ItemGroup>
</Project>

其中,主要功能可重写如下:

using System.Threading.Tasks;

...
public static async Task Main(string[] args)
{
   await BuildWebHost(args).RunAsync();
}
...

参考资料:

  1. C# 7 Series, Part 2: Async Main
  2. Champion "Async Main" (C# 7.1)

.net相关问答推荐

使用.NET 8时无法识别运行标识符

NET 6:控制器方法不可访问

使用 PEM 文件创建 DSA 签名

类似于字典但没有值的 C# 数据 struct

在 web api 控制器(.net 核心)中使用 async/await 或任务

如何在 C# 中创建表达式树来表示String.Contains("term")?

如何在任务栏顶部全屏显示 Windows 窗体?

为什么循环引用被认为是有害的?

操作对事务的状态无效错误和事务范围

如何在可取消的异步/等待中处理 TransactionScope?

我可以在没有两个查询的情况下通过布尔标准将 IEnumerable 一分为二吗?

MemoryStream.Close() 或 MemoryStream.Dispose()

在生产环境中部署调试符号(pdb 文件)有什么风险?

将月份 int 转换为月份名称

为什么 Roslyn 中有异步状态机类(而不是 struct )?

合并两个(或更多)PDF

MailMessage,Sender 和 From 属性的区别

ConfigurationManager.AppSettings - 如何修改和保存?

System.Array.CopyTo() 和 System.Array.Clone() 之间的区别

多个列表与 IEnumerable.Intersect() 的交集