C#异步和等待不起作用
为什么以下异步并等待不起作用?我试图了解这是想了解我的代码有什么问题.
class Program { static void Main(string[] args) { callCount(); } static void count() { for (int i = 0; i < 5; i++) { System.Threading.Thread.Sleep(2000); Console.WriteLine("count loop: " + i); } } static async void callCount() { Task task = new Task(count); task.Start(); for (int i = 0; i < 3; i++) { System.Threading.Thread.Sleep(4000); Console.WriteLine("Writing from callCount loop: " + i); } Console.WriteLine("just before await"); await task; Console.WriteLine("callCount completed"); } } 程序将启动count()方法,但在没有完成的情况下退出.随着等待任务;语句我希望它在退出之前等待完成count()方法的所有循环(0,1,2,3,4).我只得到“计数循环:0”.但是它经历了所有的callCount().它就像等待任务一样没有做任何事情.我希望count()和callCount()都异步运行并在完成时返回main. 解决方法
当您执行异步方法时,它会同步开始运行,直到它到达await语句,然后其余的代码异步执行,并且执行返回给调用者.
在你的代码中,callCount()开始同步运行到await任务,然后回到Main()方法,由于你没有等待方法完成,程序结束而没有方法count()可以完成. 通过将返回类型更改为Task,并在Main()方法中调用Wait(),可以看到所需的行为. static void Main(string[] args) { callCount().Wait(); } static void count() { for (int i = 0; i < 5; i++) { System.Threading.Thread.Sleep(2000); Console.WriteLine("count loop: " + i); } } static async Task callCount() { Task task = new Task(count); task.Start(); for (int i = 0; i < 3; i++) { System.Threading.Thread.Sleep(1000); Console.WriteLine("Writing from callCount loop: " + i); } Console.WriteLine("just before await"); await task; Console.WriteLine("callCount completed"); } 编辑: (为了更好地理解,允许更改CallCount()将类型返回到Task) >程序以Main()方法开头. 如果你想在CallCount()中等待count任务完成而不返回Main()方法,则调用task.Wait();,所有程序都将等待Count(),但这不是await将要做的. 这个link详细解释了async-await模式. 希望您的代码工作流程图能够帮助您. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |