Task vs ValueTask: When Should I use ValueTask?

Ғылым және технология

In this video, I address the common what is a Task vs ValueTask question.
When answering the question "When should I use a ValueTask?", you must first understand how a Task works.
A Task serves multiple purposes, but at its core it’s a “promise”. It's an object that represents the eventual completion of some operation. If a method returns a Task, regardless of if the method completes synchronously or asynchronously, the method will always allocate a new Task object in memory. This can become a problem when instances of Task objects are created a lot in methods where high-throughput and performance is a primary concern. The more allocations that are made, the more work the GC (garbage collector) will need to do.
This is where the ValueTask comes in. A ValueTask is a struct that wraps either the result, or the Task returned from an async method. This is extremely helpful in scenarios where the method can return either synchronously or asynchronously. The ValueTask will return just the value in the synchronous code path, or the Task in the asynchronous code path. Returning just the value will result in fewer allocations in memory which will improve not only the memory consumption of the method, but the executing performance as well.
In this video, I demonstrate the difference between a Task vs ValueTask as it relates to behavior. I will also show you the memory allocation and performance differences between a Task vs ValueTask.
Be sure to watch my new Pluralsight course "Introduction to Prism for WPF":
📺 bit.ly/PrismForWpf
Sponsor Me on GitHub:
🙏🏼 bit.ly/SponsorBrianOnGitHub
Get 2 Free Stocks on WeBull (Valued up to $1600 when you deposit $100)
💰 bit.ly/BrianWeBull
Follow Me:
🐦 Twitter: bit.ly/BrianLagunasOnTwitter
📖 Blog: bit.ly/BrianLagunasBlog

Пікірлер: 113

  • @andreikashin
    @andreikashin3 жыл бұрын

    It is like answering to question What is ValueTask, others return a Task and only Brian returns a VALUE immediately. Thank you, Brian.

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Very Clever! I love it!

  • @Nk54fr

    @Nk54fr

    2 жыл бұрын

    Haha I see what you did there ;D

  • @jacfarjama467
    @jacfarjama4672 жыл бұрын

    Finally someone who knows how to explain clearly. I watched other videos and couldn't comprehend why we need this ValueTask. But thanks to your clear explanation in 10 mins it all makes sense. Thanks a lot.

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Glad you liked it!

  • @ivandrofly
    @ivandrofly Жыл бұрын

    Best explanation on the internet in this topic

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    Thank you so much.

  • @CRBarchager
    @CRBarchager2 ай бұрын

    Awesome explaination. I failed to understand other explainations of this type but yours was clear and easy to understand.

  • @mahyarazad
    @mahyarazad Жыл бұрын

    I have spend almost the whole evening to understand how they differ through Microsoft blogpost, and I couldn't figure it out. Thanks for your video, I have completely understood.

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    I’m glad I could help. Thank you for watching

  • @teraformerr
    @teraformerrАй бұрын

    Another brilliant video, hope you will come back to teach us more! Thank you

  • @ChrisBoot
    @ChrisBoot3 жыл бұрын

    The best explanation I've seen for valuetask, explained in language I understood. Thank you

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    I'm glad I could help clarify it. Thanks for watching

  • @EminoMeneko
    @EminoMeneko2 жыл бұрын

    Holy cow! I was wondering the difference. So I googled it, found an article on MS blog. Did not get it. At some point there was an exemple but I could not compare because, thought there was a chapter on Task before, there was no equivalent of the example. But probably mostly because it downs clarity in too many details I could not comprehend. Maybe because of a lack of background. But here it is exactly what I need to comprehend. Right to the point as I like, good example. Simple definition. By 4mn of the video (even before) I got the point of those. Very much thank you for that.

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    I’m happy I could help. Thanks for watching

  • @amrelsher4746
    @amrelsher47462 жыл бұрын

    The best explanation I've seen for valuetask

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    I’m glad it was helpful

  • @xavhow
    @xavhow3 жыл бұрын

    You explained the best, out of a few that I have seen on KZread.

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Thank you for the kind words

  • @njezichigozie709
    @njezichigozie709 Жыл бұрын

    Thanks a lot on this Brian.

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    You’re welcome

  • @aleckendall1253
    @aleckendall12532 жыл бұрын

    Excellent explanation!

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Thank you very much

  • @debtpeon
    @debtpeon Жыл бұрын

    Excellent summary.

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    Thank you for watching

  • @fabrizziocht
    @fabrizziocht Жыл бұрын

    Finally a definitive explanation, thank you very much for your help!

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    You’re very welcome. Thank you for watching

  • @mykolakriukov1252
    @mykolakriukov1252 Жыл бұрын

    Very clear explanation, thank you!

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    Thanks for watching

  • @user-lf5sy5mv3l
    @user-lf5sy5mv3l Жыл бұрын

    What a teacher! Thank you a lot for your excellent explanation!

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    Thank you so much for the kind words

  • @eduard.schaefer
    @eduard.schaefer3 жыл бұрын

    That was a really good explanation, Brian!

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Thank you.

  • @timb00
    @timb002 жыл бұрын

    Thanks man, finally got it!

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Great to hear

  • @Pocvocem
    @Pocvocem2 жыл бұрын

    Thanks for explanation, this is the clearest.

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Thank you for watching

  • @Tamer_Ali
    @Tamer_Ali3 жыл бұрын

    Thanks a lot Brian 👍

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Very welcome

  • @11Karpovich11
    @11Karpovich112 жыл бұрын

    best explanation! Thank you!

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Thanks for watching

  • @vkg.codefactory
    @vkg.codefactory2 жыл бұрын

    Great explaination

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Thanks for watching

  • @meetrajasekar
    @meetrajasekar Жыл бұрын

    Good explanation. Thank you!!

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    Thank you for watching

  • @LoganDunning
    @LoganDunning7 ай бұрын

    thank you so much this cleared it up for me. Great explanation right to the point very easy to understand. First time I found your channel. It was the video after a Nick chapsas video in the search. Who I also enjoy. For that reason I have subscribed. I’m looking forward to future videos. Thank you Brian.

  • @christianf7740
    @christianf77402 жыл бұрын

    This is great stuff.

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    I appreciate the kind words

  • @CodingKurzgeschichten
    @CodingKurzgeschichten3 жыл бұрын

    Very nice video and great demonstration.

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Thanks for watching.

  • @nathanzimmerman6941
    @nathanzimmerman6941 Жыл бұрын

    Good presentation.

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    I appreciate you

  • @udaysuddhala3512
    @udaysuddhala35123 жыл бұрын

    This is why I consider u as my guru🙏🙏 explanation is crystal clear 👌

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Thank you so much for the kinds words sir

  • @strandloper
    @strandloper3 жыл бұрын

    Thanks, that's a nice clear explanation.

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Glad it was helpful!

  • @shreyasacharya
    @shreyasacharya2 жыл бұрын

    Awesome!

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Glad you think so!

  • @distinguishedmoments2277
    @distinguishedmoments22772 жыл бұрын

    I love your videos mate! Thanks a lot

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Thanks for watching

  • @CleberCarvalhoTI
    @CleberCarvalhoTI2 жыл бұрын

    Ottima spiegazione.

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Grazie

  • @coolfyb
    @coolfyb Жыл бұрын

    eXcellently explained.

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    Thank you so much

  • @andreapellegrini2794
    @andreapellegrini27943 жыл бұрын

    Thanks you man

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Thank you for watching

  • @tomnolane
    @tomnolane2 жыл бұрын

    thanks

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Thanks for watching

  • @ievheniiierokhin1677
    @ievheniiierokhin16773 жыл бұрын

    Thank you! I don't know that it could bring that performance, especially memory usage

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Thanks for watching

  • @davidwhite2011
    @davidwhite20113 жыл бұрын

    Compiler hot paths are code execution paths in the compiler in which most of the execution time is spent, and which are potentially executed very often. The reason for avoiding (heap) allocations in these code paths is that allocations may trigger a garbage collection, which may cause sudden, extreme performance deteriorations. These should obviously be avoided in very commonly executed code paths. Stack Overflow.

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Isn't that what I said? 😀

  • @marvinalone
    @marvinalone2 жыл бұрын

    simple, clear explaination and good benchmark/demo, thanks you ~ but I think this video can be shorter, 5mins top.

  • @mahesh_rcb
    @mahesh_rcb3 жыл бұрын

    Ctrl +shift + f Task Replace all with ValueTask 😅 Most of the time I use Task Nice explanation 👍🏻👍🏻

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Haha! When in doubt, Task is the go to. Thanks for watching

  • @adnanmaqboolkhan7522
    @adnanmaqboolkhan7522 Жыл бұрын

    Thanks for the great explanation. What happens if we use valuetask when the return type is always a task?

  • @user-mr-m12312
    @user-mr-m123123 жыл бұрын

    Great explanation Brian, thank you! ...But wait a second, where is "roll dat intro"?

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Thank you for watching. Yeah, I'm dropping the intro stuff as I dont think it provides any value. I'll just get to the point 😁

  • @peternguyen9382
    @peternguyen9382 Жыл бұрын

    Hello Brian, Thanks so much for your work. I have the question about ValueTask limitations: You said we should not run the valuetaskMethod concurrently, but when i check the Paralle.ForeachAsyn method it accept a delegate that return ValueTask. so the delegate is called multiple times ? can you help me to clearify that. Thanks so much.

  • @joakimcarlsson7826
    @joakimcarlsson78263 жыл бұрын

    Would love an explanation around yield return

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Thanks for the feedback

  • @kiranshetty8342
    @kiranshetty83423 жыл бұрын

    Hi Brian , grt video n best explanation for value task. Thanks for your help . I have an question might sound silly n apologise in advance. What exactly synchronisation context mean . Why ppl say AspNet core doesn’t support Synchronization context ??

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    Every thread has a context associated with it. The SynchronizationContext represents the location where your code is executed. It enables you to queue a task onto another context and it facilitates communication between threads. This is common used when communicating between a background thread and a UI thread (for example in WPF or WInForms). ASP.NET doesn't have a UI thread to be concerned with, and it literally does not have a SynchronizationContext class.

  • @milos5247
    @milos5247 Жыл бұрын

    Could you make a video explaining how attributes work and how to create custom ones?

  • @briannielsbergh
    @briannielsbergh2 жыл бұрын

    Isn't the cache filled in the first method, meaning that the second benchmark is using cache only?

  • @Jarenaut
    @Jarenaut3 жыл бұрын

    Nice explanation! I've a question for you... I started programming many years ago and since university studies or higher level professional training most of my programming teachers reinforce me the idea of using descriptive name and explicitly typed variables. As you can see on that time var was "forbidden". C#3.0 introduced var and C#8.0 has made nullable vars too... In dictionaries or local variables could help in readability and so..., instead you must initialize var variables and cannot assign an anonymous method to var or declare for example... Give me some light please... What's the point here¿? Thanks Brian!

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    My advice would be, use var if you like it. I like it and use it for most of my local variables. It helps keep my code clean and concise. I like to reduce redundant type information. It's shorter, easier to read, and it encourages descriptive names for your variables. Var is extremely helpful when dealing with LINQ queries too. But, it's just a personal preference. Use what you are comfortable with. The important part is that you be consistent in your code base.

  • @MarvinKleinMusic
    @MarvinKleinMusic3 жыл бұрын

    Hi Brian, could you create a video on best practises to manage data access within a blazor/c# app, without Entity Framework. I am think of this for a long time now but I don't find any solution where I say this is the perfect one. E.G. why should I use a service to access the data instead of a static method of my actual object?

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    That's a really broad topic. I'll have to think about that one. I will say that you should never use static anything for data access.

  • @MarvinKleinMusic

    @MarvinKleinMusic

    3 жыл бұрын

    @@BrianLagunas yes. I searched for this topic a while and I can only find examples regarding EF online. But I cannot use this in our project. I'm limited to writing the SQ myself. I am looking for best practises for Create/Update/Delete/Get + other method to fetch data from the database which require data from my model to run.

  • @karsten600
    @karsten6003 жыл бұрын

    Good video, I have a question though. I can't picture any instance where I'd await a task more than once, can you give an example?

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    Loading files from disk is a common one.

  • @karsten600

    @karsten600

    3 жыл бұрын

    @@BrianLagunas Thanks :)

  • @randompoints
    @randompoints3 жыл бұрын

    Can we consider ValueTask for singleton service method?

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    If the method can run either async or sync and you have benchmarked your method to determine that you would benefit from using it, then sure.

  • @TonoNamnum
    @TonoNamnum Жыл бұрын

    When having large numbers like 100000 it's easier to read it if you write it as 100_000. The compiler will make that 10000 and it's easier to read in my opinion

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    I guess I’ve been doing this so long, I don’t ever use that syntax. My eyes are just used to reading those numbers 😁. I’ll keep that In mind for demos going forward. Others my not read those numbers as easily. Thanks for the feedback.

  • @philippelhaus
    @philippelhaus3 жыл бұрын

    Sometimes i need to make sure a method is only executed once at a time by only one thread and kills everyone else that wants to get in. so i add a global bool as some sort of lock at the beginning and set it back once i exit the method. I know there’s also mutex’s for these issues, but i wonder whats really the best solution

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    If I understand you correctly, I'm pretty sure this is what the "lock" statement is for.

  • @Kumar-yn4bs
    @Kumar-yn4bs2 жыл бұрын

    Make a sample code of application using Ivaluetaskasync any example please

  • @Rob_III
    @Rob_III3 жыл бұрын

    Wait... are the benchmark results consistent even if you run them a few times? Without having tested this myself, so just going from what I see in the video (@6:30): Both GetReposAsyncTask and GetReposAsyncValueTask use the same cache object. So isn't it possible the first benchmark (which happened to be the first method) populates the cache and the second method never even goes out to Github and ONLY serves results from cache (since the other method already populated the cache)? That would also explain **a** (maybe not the entire ~20Mb) difference in allocated memory.

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    No. I tested this myself to be sure. The Benchmark harness executes each test individually as a new instance of the benchmark class.

  • @BrianLagunas

    @BrianLagunas

    3 жыл бұрын

    To be extra sure, I even changed the order in which the test invoke (ValueTask first) and the results were the same.

  • @Rob_III

    @Rob_III

    3 жыл бұрын

    @@BrianLagunas Ah, ok. I just had a hunch the _cachedRepos was maybe shared between the tests which is definitely at the very least a "gotcha" / something to look out for / be mindful of. Nice to hear and have confirmed in this case it's not. Thanks for the video!

  • @Rob_III

    @Rob_III

    3 жыл бұрын

    @@BrianLagunas Great! Again, nice to have this confirmed / double-checked ;-)

  • @ronaldmackee3401

    @ronaldmackee3401

    3 жыл бұрын

    @@BrianLagunas if the access to the cache were async too (as in distributed cache), then will ValueTask still make a difference? You can argue that the result involves async calls regardless.

  • @DickBakerSql
    @DickBakerSql Жыл бұрын

    At the end (offset=9:35) Brian should have said VALUEtask otherwise great

  • @BrianLagunas

    @BrianLagunas

    Жыл бұрын

    Isn’t that what I said 😁

  • @imixal
    @imixal2 жыл бұрын

    Can you show, when using ValueTask can be worst than Task?

  • @BrianLagunas

    @BrianLagunas

    2 жыл бұрын

    I actually covered it in this video. If you have a method that whose "hot path" is not pulling from cache, then you are better off just using Task

  • @FB-eb6tx
    @FB-eb6txАй бұрын

    Excelent video! The best explanation!

  • @BrianLagunas

    @BrianLagunas

    Ай бұрын

    Thanks for watching

Келесі