c# - 如何在 Main 中调用异步方法?

标签 c# asynchronous async-await task

public class test
{
    public async Task Go()
    {
        await PrintAnswerToLife();
        Console.WriteLine("done");
    }

    public async Task PrintAnswerToLife()
    {
        int answer = await GetAnswerToLife();
        Console.WriteLine(answer);
    }

    public async Task<int> GetAnswerToLife()
    {
        await Task.Delay(5000);
        int answer = 21 * 2;
        return answer;
    }
}

如果我想在 main() 方法中调用 Go,我该怎么做? 我正在尝试 c# 的新功能,我知道我可以将异步方法 Hook 到一个事件,并且通过触发该事件,可以调用异步方法。

但是如果我想在main方法中直接调用呢?我该怎么做?

我做了类似的事情

class Program
{
    static void Main(string[] args)
    {
        test t = new test();
        t.Go().GetAwaiter().OnCompleted(() =>
        {
            Console.WriteLine("finished");
        });
        Console.ReadKey();
    }


}

但似乎这是一个死锁,屏幕上没有打印任何内容。

最佳答案

您的 Main 方法可以简化。对于 C# 7.1 和更新版本:

static async Task Main(string[] args)
{
    test t = new test();
    await t.Go();
    Console.WriteLine("finished");
    Console.ReadKey();
}

对于早期版本的 C#:

static void Main(string[] args)
{
    test t = new test();
    t.Go().Wait();
    Console.WriteLine("finished");
    Console.ReadKey();
}

这是 async 关键字(和相关功能)的部分优点:回调的使用和混淆性质大大减少或消除。

关于c# - 如何在 Main 中调用异步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13002507/

相关文章:

Node.js Web 服务器 fs.createReadStream 与 fs.readFile?

javascript - 如何在 AngularJS 中中断/返回 Angular 异步调用

asynchronous - 发生某些情况时如何停止 Kotlin 流程

c# - 许多嵌套的聚合异常

c# - StackExchange.ConnectionMultiplexer.GetServer 不工作

c# - 当向数据库表中添加更多列时,如何让 datagridview 显示更改?

c# - 如何以编程方式在 ASP.NET MVC 5 中注册角色提供程序?

c# - 使用 Azure 移动服务进行身份验证

c# - 如何强制任务停止?

javascript - 我怎样才能让底部的 console.log 等到它全部完成,然后告诉我答案而不是等待?