如何在Main中调用异步方法? [英] How can I call an async method in 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#的新功能,我知道我可以将async方法挂接到事件上,并通过触发该事件,可以调用async方法.
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#:
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屋!