.NET Core 控制台应用程序使用异步(Async)Main方法

摘要: C# 7.1 及以上的版本容许咱们使用异步的Main方法html

C# 7.1 及以上的版本容许咱们使用异步的Main方法。git

一.新建一个控制台应用程序

1529762562337

二.异步Main方法

咱们直接将Main方法改成以下:github

static async Task Main(string[] args)

1529762747510

能够看到报错了,提示咱们是C# 7.1 的特性。咱们有两种方法能够解决,其实最后都是异曲同工,只是操做不同而已。异步

1.第一种方法-修改csproj文件

打开项目的csproj文件,添加以下代码:async

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <LangVersion>7.1</LangVersion>
  </PropertyGroup>

例如:ui

1529762909659

2.第二种方法-经过vs更改项目属性

在“解决方案管理器”界面中,选中项目,而后 右键->属性 -> Buildspa

1529763028967

在弹出的界面中选中 C# 7.1code

1529763064679

通过上面的更改之后,将不会报错了。orm

三.验证

咱们在Main方法中,加入以下代码,获取百度首页的html:htm

class Program
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        var result = await client.GetStringAsync("https://www.baidu.com/");
        Console.WriteLine(result);
        Console.ReadKey();
    }
}

而后运行:

1529763181795

本文所用代码:https://github.com/stulzq/BlogDemos/tree/master/AsyncConsoleApp

相关文章
相关标签/搜索