gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:47:15 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com