[英]If Task.Delay is to be prefered over Thread.Sleep, why examples in this book use Thread.Sleep?
I am reading Exam Ref 70-483: Programming in C# by Wouter de Kort. 我正在阅读Wouter de Kort的考试参考书70-483:《用C#编程》。
The writer doesn't explicitly mention the version of C#, but I guess it's 5.0 since he makes heavy use of async/await keywords. 作者没有明确提及C#的版本,但我猜是5.0,因为他大量使用了async / await关键字。
The examples in this book only use Thread.Sleep() and not Task.Delay() 本书中的示例仅使用Thread.Sleep(),而不使用Task.Delay()
Parallel.For(0, 10, i =>
{
Thread.Sleep(1000);
});
, ,
Task.Run(() =>
{
bag.Add(42);
Thread.Sleep(1000);
bag.Add(21);
});
etc etc... 等等等等
From other reading/SO questions like this , I'd figure that 从其他阅读/ SO这样的问题这样 ,我的身影,
await Task.Delay(1000)
should generally do better in a parallel context than 通常在并行环境中应该比
Thread.Sleep(1000)
because Task.Delay leaves it's thread unhindered thus allowing other tasks execute on it. 因为Task.Delay使其线程不受阻碍,从而允许其他任务在其上执行。
I've just Ctrl-F'd the book and it didn't find a single occurrence for Task.Delay! 我只按Ctrl-F键就可以找到这本书,但找不到Task.Delay的任何地方! I'm confused between community opinions from the internet and official Microsoft book. 我对互联网上的社区意见和Microsoft官方书籍感到困惑。
If Task.Delay is a good practice, why doesn't this book address it in any way? 如果Task.Delay是一个好习惯,那么为什么本书没有以任何方式解决它?
Or did I miss something? 还是我错过了什么?
The other question deals with real-world code; 另一个问题涉及实际代码。 what you have in your book are code examples, which are quite different. 您的书中有一些代码示例,它们完全不同。
For code examples: 对于代码示例:
Thread.Sleep
is appropriate if you want to block the current thread - ie, you're simulating some synchronous / CPU-bound work. 如果您想阻塞当前线程,则Thread.Sleep
是合适的-即,您正在模拟一些同步/ CPU约束的工作。
Task.Delay
is appropriate if you don't want to block the current thread - ie, you're simulating some asynchronous / I/O-bound work. Task.Delay
即你正在模拟一些异步/ I / O限制的工作-如果你不希望阻止当前线程是适当的。
For the particular examples you posted (code in Parallel.For
and Task.Run
), I'd say Thread.Sleep
is the most appropriate. 对于您发布的特定示例( Parallel.For
和Task.Run
代码),我想说Thread.Sleep
是最合适的。 Parallel.For
and Task.Run
are specifically for running CPU-bound code on different threads, so a synchronous "placeholder" of Thread.Sleep
is correct. Parallel.For
和Task.Run
专用于在不同线程上运行CPU绑定的代码,因此Thread.Sleep
的同步“占位符”是正确的。
Note that in real-world code, any "placeholder" usages of Thread.Sleep
and Task.Delay
like this are replaced with real code. 请注意,在实际代码中,像这样的Thread.Sleep
和Task.Delay
任何“占位符”用法都将替换为真实代码。
In real-world code, Task.Delay
is still useful for things like delayed retries. 在现实世界的代码中, Task.Delay
对于延迟重试之类的事情仍然有用。 Thread.Sleep
should not be in real-world code. Thread.Sleep
不应在实际代码中。
Exam 70-483 is for Visual Studio 2012, when C# had no async/await. 当C#没有异步/等待时,考试70-483适用于Visual Studio 2012。
Also, the Thread.Sleep()
is just there to indicate work being done. 另外, Thread.Sleep()
只是在这里指示正在完成的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.