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

编程入门 行业动态 更新时间:2024-10-25 11:19:37
本文介绍了如何在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中调用异步方法?

本文发布于:2023-11-14 13:32:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587347.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   如何在   Main

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!