摘要: 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