As you discovered, in VS11 the compiler will disallow an async Main method. This was allowed (but never recommended) in VS2010 with the Async CTP.

I have recent blog posts about async/await and asynchronous console programs in particular. Here's some background info from the intro post:

If "await" sees that the awaitable has not completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method. Await will also capture the current context when it passes the remainder of the method to the awaitable.

Later on, when the awaitable completes, it will execute the remainder of the async method (within the captured context).

Here's why this is a problem in Console programs with an async Main:

Remember from our intro post that an async method will return to its caller before it is complete. This works perfectly in UI applications (the method just returns to the UI event loop) and ASP.NET applications (the method returns off the thread but keeps the request alive). It doesn't work out so well for Console programs: Main returns to the OS - so your program exits.

One solution is to provide your own context - a "main loop" for your console program that is async-compatible.

If you have a machine with the Async CTP, you can use GeneralThreadAffineContext from My Documents\Microsoft Visual Studio Async CTP\Samples(C# Testing) Unit Testing\AsyncTestUtilities. Alternatively, you can use AsyncContext from my Nito.AsyncEx NuGet package.

Here's an example using AsyncContextGeneralThreadAffineContext has almost identical usage:

using Nito.AsyncEx;
class Program
{
static void Main(string[] args)
{
AsyncContext.Run(() => MainAsync(args));
} static async void MainAsync(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
}

Alternatively, you can just block the main Console thread until your asynchronous work has completed:

class Program
{
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
} static async Task MainAsync(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
}

Note the use of GetAwaiter().GetResult(); this avoids the AggregateException wrapping that happens if you use Wait() or Result.

Update, 2017-11-30: As of Visual Studio 2017 Update 3 (15.3), the language now supports an async Main - as long as it returns Task or Task<T>. So you can now do this:

class Program
{
static async Task Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
}

The semantics appear to be the same as the GetAwaiter().GetResult() style of blocking the main thread. However, there's no language spec for C# 7.1 yet, so this is only an assumption.

https://stackoverflow.com/questions/9208921/cant-specify-the-async-modifier-on-the-main-method-of-a-console-app

C# Main函数中调用异步方法的2种实现的更多相关文章

  1. java中main函数怎么调用外部非static方法

    使用外部方法时(不管是static还是非static),都要先new一个对象,才能使用该对象的方法. 举例如下: 测试函数(这是错误的): public class Test { public sta ...

  2. eclipse 中main()函数中的String[] args如何使用?通过String[] args验证账号密码的登录类?静态的主方法怎样才能调用非static的方法——通过生成对象?在类中制作一个方法——能够修改对象的属性值?

    eclipse 中main()函数中的String[] args如何使用? 右击你的项目,选择run as中选择 run configuration,选择arguments总的program argu ...

  3. 在信号处理函数中调用longjmp

    错误情况及原因分析 前两天看APUE的时候,有个程序要自己制作一个sleep程序,结果在这个程序中就出现了在信号处理函数中调用longjmp函数的情况,结果就出现了错误,具体错误是啥呢,请参见下面这段 ...

  4. linux中应用程序main函数中没有开辟进程的,它应该在那个进程中运行呢?

    1.main函数是一个进程还是一个线程? 不知道你是用c创建的,还是用java创建的. 因为它们都是以main()做为入口开始运行的. 是一个线程,同时还是一个进程. 在现在的操作系统中,都是多线程的 ...

  5. (转)Java程序利用main函数中args参数实现参数的传递

    Java程序利用main函数中args参数实现参数的传递 1.运行Java程序的同时,可以通过输入参数给main函数中的接收参数数组args[],供程序内部使用!即当你在Java命令行后面带上参数,J ...

  6. 在类的成员函数中调用delete this

    最近面试的时候被问到一个问题是,在C++中,能否在类的成员函数中调用delete this,后来网上查了一下资料,关于这个问题说得比较好的有http://blog.sina.com.cn/s/blog ...

  7. [原创]C/C++语言中,如何在main.c或main.cpp中调用另一个.c文件

    C/C++语言中,如何在main.cpp中调用另一个.c文件主要有5种思路: 1.在VS2012 IDE中,将被引用的.c文件后缀名全部修改为.h,然后通过IDE的解决方案资源管理器中鼠标右键单击“头 ...

  8. 问题:C#控制台程序参数;结果:设置与读取C#控制台应用程序Main函数中的参数args

    设置与读取C#控制台应用程序Main函数中的参数args 在项目属性面版->调试->命令行参数设置.空格分隔.读取:string[] str = Environment.GetComman ...

  9. .NET中如何在同步代码块中调用异步方法

    更新记录 本文迁移自Panda666原博客,原发布时间:2021年7月2日. 在同步代码块中调用异步方法,方法有很多. 一.对于有返回值的Task 在同步代码块中直接访问 Task 的 Result ...

随机推荐

  1. 【Linux】gdb调试

    g++ -g ... gdb l    列出代码,回车键继续 break main / 行号 加断点 n    单步运行 s    单步运行(可进入函数) p    输出变量 p *array@len ...

  2. ajax 提交数组 泛型集合

    ajax 提交数组 泛型集合 发表于2015/12/31 14:26:29  5117人阅读 分类: mvc asp.net webapi ORM 转载:http://blog.csdn.net/li ...

  3. Ubuntu LNMP系统搭建Zabbix监控

    系统环境 操作系统类型:Ubuntu 系统环境版本:4.4.0-122-generic IP地址:192.168.152.118 第一步:选择适当的操作系统类型与各项的版本要求,我这边直接使用LNMP ...

  4. Jenkins安装使用教程

    一.说明 持续集成:Continuous integration,CI.包括两层含义,一是指项目的每个开发人员每天都向项目代码仓库要通过git等提交他们的代码,二是指在代码提交后实现自动化的构建.部署 ...

  5. Oracle 11g OGG 修改 trail 文件大小

    OGG 修改 trail 文件大小 2018-06-11 15:14 380 0 原创 GoldenGate 本文链接:https://www.cndba.cn/leo1990/article/285 ...

  6. Vultr新用户充值优惠 – 最多充值100美元送100美元

    Vultr商家向来是搅局的,当初海外VPS商家被Linode一家独大的时候,由于VULTR商家进入市场进行相似产品的营销,使得目前我们看到海外主机商各种低价.当然这些说法也有些武断,但是肯定是有一定的 ...

  7. tomcat8常用配置说明

    链接:https://www.jianshu.com/p/8b1c75951f70 2.tomcat8运行期错误HTTP头解析错误 修改tomcat的server.xml中的中配置  设置为8k &l ...

  8. impala和kudu使用的小细节

    七堇年:我们要有最朴素的生活与最遥远的梦想 . 即使明日天寒地冻,路远马亡.   加油! 之前入门的小错误总结,建表都会出错,真的好尴尬 还是要做好笔记 第一个错误: error:AnalysisEx ...

  9. uboot中往s5p6818的emmc刷写内容

    建立分区: fdisk :: : fdisk Partition Map -- Partition Type: DOS Part Start Sector Num Sectors UUID Type ...

  10. c#分布式ID生成器

    c#分布式ID生成器   简介 这个是根据twitter的snowflake来写的.这里有中文的介绍. 如上图所示,一个64位ID,除了最左边的符号位不用(固定为0,以保证生成的ID都是正数),还剩余 ...