我有一个简单的代码:

public static async Task<int> SumTwoOperationsAsync()
{
    var firstTask = GetOperationOneAsync();
    var secondTask = GetOperationTwoAsync();
    return await firstTask + await secondTask;
}


private async Task<int> GetOperationOneAsync()
{
    await Task.Delay(500); // Just to simulate an operation taking time
    return 10;
}

private async Task<int> GetOperationTwoAsync()
{
    await Task.Delay(100); // Just to simulate an operation taking time
    return 5;
}

太好了。这个编译。

但是,假设我有一个控制台应用程序,我想运行上面的代码(调用SumTwoOperationsAsync())。

static void Main(string[] args)
{
     SumTwoOperationsAsync();
}

但我读到过(当使用sync时)我必须上下同步:

这是否意味着我的Main函数应该被标记为async?

不可能,因为有编译错误:

入口点不能用'async'修饰符标记

如果我理解了异步的东西,线程将进入Main函数→SumTwoOperationsAsync→将调用两个函数并将退出。但是直到SumTwoOperationsAsync

我错过了什么?


在大多数项目类型中,你的async“up”和“down”将结束于一个async void事件处理程序或返回一个Task到你的框架。

然而,控制台应用程序不支持这一点。

你可以对返回的任务执行一个Wait:

static void Main()
{
  MainAsync().Wait();
  // or, if you want to avoid exceptions being wrapped into AggregateException:
  //  MainAsync().GetAwaiter().GetResult();
}

static async Task MainAsync()
{
  ...
}

或者你可以使用你自己的上下文,就像我写的那样:

static void Main()
{
  AsyncContext.Run(() => MainAsync());
}

static async Task MainAsync()
{
  ...
}

关于异步控制台应用程序的更多信息在我的博客上。


这是最简单的方法

static void Main(string[] args)
{
    Task t = MainAsync(args);
    t.Wait();
}

static async Task MainAsync(string[] args)
{
    await ...
}

作为一个快速和非常范围的解决方案:

的任务。结果

这两个任务。结果和任务。当与I/O一起使用时,Wait不能提高可伸缩性,因为它们会导致调用线程保持阻塞状态,等待I/O结束。

当你在一个未完成的任务上调用. result时,执行该方法的线程必须等待任务完成,这将阻塞线程在此期间做任何其他有用的工作。这就否定了任务异步特性的好处。

公定异步


我的解决方案。JSONServer是我为在控制台窗口中运行HttpListener服务器而编写的类。

class Program
{
    public static JSONServer srv = null;

    static void Main(string[] args)
    {
        Console.WriteLine("NLPS Core Server");

        srv = new JSONServer(100);
        srv.Start();

        InputLoopProcessor();

        while(srv.IsRunning)
        {
            Thread.Sleep(250);
        }

    }

    private static async Task InputLoopProcessor()
    {
        string line = "";

        Console.WriteLine("Core NLPS Server: Started on port 8080. " + DateTime.Now);

        while(line != "quit")
        {
            Console.Write(": ");
            line = Console.ReadLine().ToLower();
            Console.WriteLine(line);

            if(line == "?" || line == "help")
            {
                Console.WriteLine("Core NLPS Server Help");
                Console.WriteLine("    ? or help: Show this help.");
                Console.WriteLine("    quit: Stop the server.");
            }
        }
        srv.Stop();
        Console.WriteLine("Core Processor done at " + DateTime.Now);

    }
}