c# - .NET Core 是否支持异步控制台应用程序?

标签 c# .net .net-core

在某个时间点,CoreCLR 支持异步主入口点。参见 http://blog.stephencleary.com/2015/03/async-console-apps-on-net-coreclr.html

但是,以下两个程序都无法在 .NET Core 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 World!");
        }
    }
}

using System;
using System.Threading.Tasks;

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

这些都因错误而失败:

error CS5001: Program does not contain a static 'Main' method suitable for an entry point

.NET Core 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# 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>

其中 Main 函数可以重写如下:

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)

关于c# - .NET Core 是否支持异步控制台应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38114553/

相关文章:

c# - 在 WPF UserControl 上应用样式的问题

c# - Process.Start权限问题

c# - Entity Framework Core 中没有嵌套结果

javascript - 在为图表动态创建持有者后渲染图表不起作用

.net-core - .NET Core 依赖树

c# - 将 html 保存到 csv 并使用 Excel 打开

c# - AllowDrop 属性不适用于 ToolStripItems

c# - Entity Framework 无法从存储的 MySql 正确创建复杂类型

c# - 多线程与datagridview

.net - .NET 中的稀疏多维数组或矩阵库