简体   繁体   English

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

[英]Are async console applications supported in .NET Core?

At some point in time the CoreCLR supported async main entry points.在某个时间点,CoreCLR 支持异步主入口点。 See http://blog.stephencleary.com/2015/03/async-console-apps-on-net-coreclr.htmlhttp://blog.stephencleary.com/2015/03/async-console-apps-on-net-coreclr.html

However both the following programs are not working in .NET Core RTM但是,以下两个程序都无法在 .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!");
        }
    }
}

or

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!");
        }
    }
}

These both fail with the error:这些都失败并出现错误:

error CS5001: Program does not contain a static 'Main' method suitable for an entry point错误 CS5001:程序不包含适合入口点的静态“Main”方法

Are async console applications supported in .NET Core RTM? .NET Core RTM 是否支持异步控制台应用程序?

Yes, the async Main functions are supported since .NET Core 2.0 .是的,从.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

The support for the async Main functions is introduced in C# version 7.1. C# 7.1 版中引入了对async Main函数的支持。 However, this functionality is not available out of the box.但是,此功能不是开箱即用的。 To make use of this feature you need explicitly specify the C# version 7.1 in your .csproj file, either by including要使用此功能,您需要在.csproj文件中明确指定 C# 版本 7.1,或者通过包含

<LangVersion>latest</LangVersion>

or by或由

<LangVersion>7.1</LangVersion>

For example for the ASP.NET core 2.0 project:例如对于 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>

where the Main function can be rewritten as following:其中 Main 函数可以重写如下:

using System.Threading.Tasks;

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

References:参考资料:

  1. C# 7 Series, Part 2: Async Main C# 7 系列,第 2 部分:异步主
  2. Champion "Async Main" (C# 7.1)冠军“异步主”(C# 7.1)

Update : Async main is supported natively by C# 7.1!更新:Async main 由 C# 7.1 原生支持! See Evgeny's answer above.请参阅上面 Evgeny 的回答

I'll keep the below workaround for posterity, but it is no longer needed.我会为后代保留以下解决方法,但不再需要它。 async main is way simpler, use that if you can! async main更简单,如果可以,请使用它!


This is my preferred workaround in C# less than 7.1 :这是我在低于 7.1 的 C# 中首选的解决方法:

using System;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            MainAsync(args).GetAwaiter().GetResult();

            Console.ReadKey();
        }

        public static async Task MainAsync(string[] args)
        {
            await Task.Delay(1000);
            Console.WriteLine("Hello World!");
        }
    }
}

GetAwaiter().GetResult() is the same as .Wait (blocking synchronously), but is preferred because it unwraps exceptions. GetAwaiter().GetResult()是相同的.Wait (同步阻塞),但是是优选的,因为它解开异常。

Support for async entry points was removed a while back.不久前删除了对异步入口点的支持。

See this issue on the aspnet/announcements github.请在 aspnet/announcements github 上查看此问题

We decided to move towards unification of entry point semantics with desktop CLR.我们决定将入口点语义与桌面 CLR 统一起来。

Obsolete in RC1:在 RC1 中已过时:

Support for async/Task<> Main.支持 async/Task<> Main。

Support for instantiating of entry point type (Program).支持入口点类型(程序)的实例化。

The Main method should be public static void Main or public static int Main. Main 方法应该是 public static void Main 或 public static int Main。

Support for injecting dependencies into the Program class's constructor and Main method.支持将依赖项注入到 Program 类的构造函数和 Main 方法中。

Use PlatformServices and CompilationServices instead.请改用 PlatformServices 和 CompilationServices。

To get to IApplicationEnvironment, IRuntimeEnvironment, IAssemblyLoaderContainer, IAssemblyLoadContextAccessor, ILibraryManager use Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default static object.要访问 IApplicationEnvironment、IRuntimeEnvironment、IAssemblyLoaderContainer、IAssemblyLoadContextAccessor、ILibraryManager,请使用 Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default 静态对象。

To get to ILibraryExporter, ICompilerOptionsProvider use the Microsoft.Extensions.CompilationAbstractions.CompilationServices.Default static object.要访问 ILibraryExporter,ICompilerOptionsProvider 使用 Microsoft.Extensions.CompilationAbstractions.CompilationServices.Default 静态对象。

Support for CallContextServiceLocator.支持 CallContextServiceLocator。 Use PlatformServices and CompilationServices instead.请改用 PlatformServices 和 CompilationServices。

Same as above.和上面一样。

These would be removed in RC2: #106这些将在 RC2 中删除:#106

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 .net core web API 对 .net 控制台应用程序进行身份验证 - Authenticating .net console applications with .net core web API “ProtoCompile”任务不支持 AdditionalProtocArguments”参数,.Net Core 控制台应用程序 - AdditionalProtocArguments" parameter is not supported by the "ProtoCompile" task, .Net Core Console app 如何为.NET Core控制台应用程序创建exe? - How can I create an exe for .NET Core console applications? NltkNet NLTK 包装器 class 是否支持 .NET 核心 web 应用程序或仅控制台应用程序? - Does NltkNet the NLTK wrapper class support .NET core web applications or only console applications? .Net Core不支持UserPasswordCredential - UserPasswordCredential not supported with .Net Core 调用Application.Run()或实例化WinForms UserControl对象时,在.NET Console中使用Async / Await中断应用程序 - Utilizing Async/Await in .NET Console applications breaks when calling Application.Run() or instantiating a WinForms UserControl object 异步无效方法如何报告 ASP.NET 核心应用程序中的进度 - How do async void methods report progress in ASP.NET Core applications 使用.NET核心的异步请求 - Async requests with .NET core .Net Core Linux 不支持安全标识符? - SecurityIdentifier not supported on .Net Core Linux? .NET Core 2.1 EventWaitHandle不受支持? - .NET Core 2.1 EventWaitHandle Not Supported?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM