Task.Delay如何正确工作?

编程入门 行业动态 更新时间:2024-10-25 04:26:59
本文介绍了Task.Delay如何正确工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

他们说Task.Delay()是异步Thread.Sleep().为了测试这一点,我写了下面的代码.我希望立即打印一个",然后3秒后将打印结果变量(15).此后2秒钟,将打印"Two".但事实并非如此.不会立即打印一个".3秒钟后打印一个".为什么要等待3秒钟才能打印一个"?

They say Task.Delay() is an async Thread.Sleep(). To test this I wrote below code. I expect to print immediately "One" then 3 seconds later result variable (15) will be printed. 2 seconds after this, "Two" will be printed. But it doesnt seem so. "One" is not immediately printed. "One" is printed 3 seconds later. Why does it wait 3 seconds to print "One" ?

using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication31 { class Program { public static int Multiply(int a, int b) { return a * b; } public static async Task DoRunAsync(int m, int n) { int result = await Task.Run(() => Multiply(m, n)); await Task.Delay(3000); Console.WriteLine("One"); Console.WriteLine(result); } static void Main(string[] args) { Task t = DoRunAsync(3, 5); Thread.Sleep(5000); Console.WriteLine("Two"); } } }

推荐答案

打印"One" 大约需要3秒钟,因为您 await -ed Task.延迟太早了.

It takes 3 seconds to print "One" because you await-ed Task.Delay too soon.

按如下所示更改代码以得到您期望的结果:

Change the code as follows to get the result that you expected:

int result = await Task.Run(() => Multiply(m, n)); var taskDelay = Task.Delay(3000); // No blocking here, so Console.WriteLine("One"); // printing can proceed. await taskDelay; // This causes a block for the remainder of 3 seconds Console.WriteLine(result);

当您在打印"One" 之前启动延迟任务而没有 await 对其进行操作时,后续的 WriteLine 可以立即完成.

When you start the delay task prior to printing "One" without await-ing it, subsequent WriteLine could complete without a delay.

更多推荐

Task.Delay如何正确工作?

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

发布评论

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

>www.elefans.com

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