evictednoise
evictednoise

Reputation: 593

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.
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.

The examples in this book only use Thread.Sleep() and not 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

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.
I've just Ctrl-F'd the book and it didn't find a single occurrence for Task.Delay! I'm confused between community opinions from the internet and official Microsoft book.
If Task.Delay is a good practice, why doesn't this book address it in any way?
Or did I miss something?

Upvotes: 0

Views: 592

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456437

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 - i.e., you're simulating some synchronous / CPU-bound work.

Task.Delay is appropriate if you don't want to block the current thread - i.e., you're simulating some asynchronous / I/O-bound work.

For the particular examples you posted (code in Parallel.For and Task.Run), I'd say Thread.Sleep is the most appropriate. Parallel.For and Task.Run are specifically for running CPU-bound code on different threads, so a synchronous "placeholder" of Thread.Sleep is correct.

Note that in real-world code, any "placeholder" usages of Thread.Sleep and Task.Delay like this are replaced with real code.

In real-world code, Task.Delay is still useful for things like delayed retries. Thread.Sleep should not be in real-world code.

Upvotes: 2

CodeCaster
CodeCaster

Reputation: 151586

Exam 70-483 is for Visual Studio 2012, when C# had no async/await.

Also, the Thread.Sleep() is just there to indicate work being done.

Upvotes: 0

Related Questions