如何在 Main 中调用异步方法? [英] How can I call an async method in Main?

查看:62
本文介绍了如何在 Main 中调用异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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# 新功能,我知道我可以将异步方法挂钩到事件,并通过触发该事件,可以调用异步方法.

if I want to call Go in main() method, how can I do that? I am trying out c# new features, I know i can hook the async method to a event and by triggering that event, async method can be called.

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

But what if I want to call it directly in main method? How can i do that?

我做了类似的事情

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


}

但似乎是死锁,屏幕上什么也没有打印.

But seems it's a dead lock and nothing is printed on the screen.

推荐答案

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

Your Main method can be simplified. For C# 7.1 and newer:

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

对于早期版本的 C#:

For earlier versions of C#:

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

这是 async 关键字(和相关功能)的美妙之处的一部分:回调的使用和混淆性质大大减少或消除.

This is part of the beauty of the async keyword (and related functionality): the use and confusing nature of callbacks is greatly reduced or eliminated.

这篇关于如何在 Main 中调用异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆