他们说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如何正确工作?
发布评论