DEV Community

Cover image for C# Async Await, Simply

C# Async Await, Simply

Henrick Tissink on September 26, 2019

One at a time Code is executed to achieve a purpose. Usually it's run as a series of steps, eventually leading to a final result. Each o...
Collapse
 
glsolaria profile image
G.L Solaria

I understand why you are using Thread.Sleep (to mimic doing some CPU intensive work) but I fear it will also give beginners the wrong impression about using Thread.Sleep in tasks to delay work. I think instead of ...

public static async Task WorldDomination()
{
    await Task.Run(() =>
    {
        Thread.Sleep(6000);
        Console.WriteLine("World Domination Achieved!");
    });
}
Enter fullscreen mode Exit fullscreen mode

If you need to delay before doing something in a task ...

public static async Task WorldDomination()
{
    await Task.Delay(6000);
    Console.WriteLine("World Domination Achieved!");
}
Enter fullscreen mode Exit fullscreen mode

If you Thread.Sleep in many running tasks, performance may suffer. If you do it to excess, work may have to be queued waiting for all the sleeping threads to wake and finish executing their work. At the very worst you could get out of memory exceptions.

Like I said I understand why you chose to use Thread.Sleep for your example but beginners shouldn't think that using Thread.Sleep in tasks is good practice.

Helping others understand async/await is no mean feat. Good on you for giving it a go.

Collapse
 
htissink profile image
Henrick Tissink

You make a good point. Awaiting a Task.Delay is much better - Thread.Sleep was just used for the illustration. I'll fix it when I get the chance :)

Collapse
 
ronaldjenkins profile image
David Swayze

I keep reading a lot of posts when I first get into trouble. This is how I once reached this website (kodlogs.net/1/task-delay-vs-thread...) and got the desired solution. You can read this post as well as visit here. I think it will be very useful for you

Collapse
 
nenadj profile image
Nenad

If you are worried about beginners than explain them !

Collapse
 
negue profile image
negue

If you starting a new Task.Run or having a Task in a method without something to do after it, you don't need to async/await it in the method.

Example, instead of:

public static async Task<int> MakeOneMillionDollars()
{
    return await Task.Run(() =>
    {
        Console.WriteLine("Million Dollars Made!");
                return 1000000;
    });
}

you can just write this:

public static Task<int> MakeOneMillionDollars()
{
    return Task.Run(() =>
    {
        Console.WriteLine("Million Dollars Made!");
        return 1000000;
    });
}

This removes some async/await overhead :)

Also as already mentioned Task.Delay instead of Thread.Sleep

Collapse
 
vekzdran profile image
Vedran Mandić

Good point, but also it should always be taken with great care in production scenarios that utilize try/catch in similar code as now you are risking of not having the exception unwrapped in the MakeOneMillionDollars due to not awaiting it here explicitly. But the perf tip is on point as this code will produce one compiler generated type less with its following state machine.

Collapse
 
kryptosfr profile image
Nicolas Musset • Edited

I quote "Awaiting asynchronous code, two things happen. A thread is taken from the thread pool and allocated to the asynchronous operation".

That's just wrong and a big misunderstanding of async/await. Asynchrony doesn't need to get threads from the thread pool or otherwise.

In your case it just happens because you used Task.Run but that's a edge case and actually not a good practice with async/await (Task.Run is more suited with TPL but you can use async/await when you combine with other asynchronous calls). Most asynchronous code never consumes threads.

See blog.stephencleary.com/2013/11/the...

That said I did enjoy reading the article. But that's because I'm evil!

Collapse
 
htissink profile image
Henrick Tissink

Hi, I appreciate your comment - and you are partially correct.

It's up to the scheduler to determine if a new thread is needed. It may or may not spin up a new thread. I'll clarify it when I have a chance.

Collapse
 
kryptosfr profile image
Nicolas Musset

It is a bit more than that actually. Your example demonstrates parallel computation not asynchrony. Task.Run never creates asynchronous code, whether the scheduler decides to run it immediatly on the same thread, or to schedule it on a worker.

It is understandable to be confused since most of us (me included) started to use tasks when async/await got out. But the Task type was originally created for parallel computing with the TPL (hence why it is in a System.Threading sub-namespace). Asynchronous task (also called future or promise in other languages) should have used a different type but the .Net team decided to reuse Task for that purpose. It does lead to a unified model where we can combine both, but it also adds to the confusion.

I think a better example would be to use sockets or file asynchronous reading/writing, which doesn't involve any threads.

Thread Thread
 
htissink profile image
Henrick Tissink

Thanks for the explanation (and the link) Nicolas :) you really taught me something valuable today.

Collapse
 
peledzohar profile image
Zohar Peled • Edited

Nice one, and perhaps it's just me, but I find your lack of faith distur... No, wait, I find your usage of animated gifs disturbing. IMHO, There's way too many of them in an otherwise really good and simple (and funny! that counts!) introduction to async programming.

Collapse
 
htissink profile image
Henrick Tissink

Thanks for the feedback - I always appreciate constructive criticism. I'll try and find a better balance for the gifs.

Collapse
 
mburszley profile image
Maximilian Burszley

(voice) I appreciated the gifs.

Thread Thread
 
jack profile image
Jack Williams

I read this article because of the gifs 😆

Thread Thread
 
luturol profile image
Rafael Ahrons

The gifs made it very funny to read and learn

Collapse
 
sainathsurender profile image
sainathsurender

I feel having gifs makes it interesting for beginners and makes them wanna read it till the end. Keep it up @henrick

Collapse
 
wreckitrob profile image
Rob

This is probably the first time I've fully understood async and await and the benefits it provides all while being an interesting and fun.

Thank you.

Collapse
 
htissink profile image
Henrick Tissink

Thanks for the compliment Rob :) I really appreciate it.

Collapse
 
luturol profile image
Rafael Ahrons

I loved the article!!

I've never understood async/await until now, and had to extract all those methods to another one and had it called from Main using .Wait(). I was like "Damn, that is good use and explanation" while laughing a lot

Collapse
 
vikasjk profile image
Vikas-jk

Good article, If someone stumbles upon this and want to read more about async-await in MVC, take a look
Asynchronous programming in C# and ASP.NET MVC ( With example )

Collapse
 
bellonedavide profile image
Davide Bellone

Cool!
A nice thing to know is that if the return type of a method is Task<int> you can return simply int and have .net work for you :)

code4it.dev/blog/asynchronous-prog...

Collapse
 
coderlegi0n profile image
CoderLegion

Task. Sleep is a synchronous thread that puts the thread to sleep so it can't be used for anything else. Task, on the other hand. Delay is an asynchronous thread that can be used to perform other tasks while it waits. Refer to this kodlogs.net/1/task-delay-vs-thread...

Collapse
 
lukegarrigan profile image
Luke Garrigan

Brilliant work mate, good to see some genuinely good content mixed in with humour. Thanks for this.

Collapse
 
htissink profile image
Henrick Tissink

Appreciate the positive feedback Luke! :)

Collapse
 
jack profile image
Jack Williams

*One Meeeelion Dollars

Collapse
 
jamietwells profile image
jamietwells

There are so many misconceptions and bad habits in this article. Please update it with better code examples and clear up the misconceptions like the conflation between async and threads.

Collapse
 
elleattwell profile image
Harry Balls

I like how you explained this, very simple.

Collapse
 
madebygps profile image
Gwyneth Peña-Siguenza

Fantastic explanation and I finally understand this topic! Haven't seen any recent posts of yours but I hope you continue to make some soon :)

Collapse
 
salem309 profile image
Ahmed Salem

Well written Henrick!!

Collapse
 
daverubin profile image
DaveRubin

Nice piece man!
Kudos

Collapse
 
mihirpa98294668 profile image
mihir patel

Very good web page, thank oneself for the exciting material for guaranteed I am going to be back.
kodlogs.net/1/task-delay-vs-thread...