如果我想在 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 中调用异步方法?
发布评论