.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

相關文章
相關標籤/搜索