摘要: C# 7.1 及以上的版本容許咱們使用異步的Main方法html
C# 7.1 及以上的版本容許咱們使用異步的Main方法。git
咱們直接將Main方法改成以下:github
static async Task Main(string[] args)
能夠看到報錯了,提示咱們是C# 7.1 的特性。咱們有兩種方法能夠解決,其實最後都是異曲同工,只是操做不同而已。異步
打開項目的csproj文件,添加以下代碼:async
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <LangVersion>7.1</LangVersion> </PropertyGroup>
例如:ui
在「解決方案管理器」界面中,選中項目,而後 右鍵->屬性 -> Buildspa
在彈出的界面中選中 C# 7.1
code
通過上面的更改之後,將不會報錯了。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(); } }
而後運行:
本文所用代碼:https://github.com/stulzq/BlogDemos/tree/master/AsyncConsoleApp