Task vs ValueTask: When Should I use ValueTask?

Sdílet
Vložit
  • čas přidán 14. 04. 2021
  • 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
  • Věda a technologie

Komentáře • 113

  • @andreikashin
    @andreikashin Před 3 lety +27

    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  Před 3 lety

      Very Clever! I love it!

    • @Nk54fr
      @Nk54fr Před 2 lety

      Haha I see what you did there ;D

  • @jacfarjama467
    @jacfarjama467 Před 2 lety +9

    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.

  • @ivandrofly
    @ivandrofly Před 11 měsíci +3

    Best explanation on the internet in this topic

  • @CRBarchager
    @CRBarchager Před 28 dny

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

  • @teraformerr
    @teraformerr Před 10 dny

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

  • @mahyarazad
    @mahyarazad Před rokem +1

    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  Před rokem

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

  • @EminoMeneko
    @EminoMeneko Před 2 lety +2

    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  Před 2 lety

      I’m happy I could help. Thanks for watching

  • @ChrisBoot
    @ChrisBoot Před 3 lety +3

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

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

  • @LoganDunning
    @LoganDunning Před 5 měsíci

    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.

  • @debtpeon
    @debtpeon Před rokem +1

    Excellent summary.

  • @amrelsher4746
    @amrelsher4746 Před 2 lety +1

    The best explanation I've seen for valuetask

  • @aleckendall1253
    @aleckendall1253 Před 2 lety +1

    Excellent explanation!

  • @mykolakriukov1252
    @mykolakriukov1252 Před rokem +1

    Very clear explanation, thank you!

  • @nathanzimmerman6941
    @nathanzimmerman6941 Před rokem +1

    Good presentation.

  • @njezichigozie709
    @njezichigozie709 Před rokem +1

    Thanks a lot on this Brian.

  • @xavhow
    @xavhow Před 3 lety +1

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

  • @meetrajasekar
    @meetrajasekar Před rokem +1

    Good explanation. Thank you!!

  • @eduard.schaefer
    @eduard.schaefer Před 3 lety +5

    That was a really good explanation, Brian!

  • @Pocvocem
    @Pocvocem Před 2 lety +1

    Thanks for explanation, this is the clearest.

  • @vkg.codefactory
    @vkg.codefactory Před 2 lety +1

    Great explaination

  • @user-mr-m12312
    @user-mr-m12312 Před 3 lety +3

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +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 😁

  • @udaysuddhala3512
    @udaysuddhala3512 Před 3 lety +1

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +1

      Thank you so much for the kinds words sir

  • @fabrizziocht
    @fabrizziocht Před rokem +1

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

    • @BrianLagunas
      @BrianLagunas  Před rokem

      You’re very welcome. Thank you for watching

  • @CodingKurzgeschichten
    @CodingKurzgeschichten Před 3 lety +1

    Very nice video and great demonstration.

  • @user-lf5sy5mv3l
    @user-lf5sy5mv3l Před rokem +1

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

  • @FB-eb6tx
    @FB-eb6tx Před 19 dny +1

    Excelent video! The best explanation!

  • @11Karpovich11
    @11Karpovich11 Před 2 lety +1

    best explanation! Thank you!

  • @davidwhite2011
    @davidwhite2011 Před 3 lety +2

    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.

  • @briannielsbergh
    @briannielsbergh Před 2 lety +1

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

  • @Tamer_Ali
    @Tamer_Ali Před 3 lety +1

    Thanks a lot Brian 👍

  • @timb00
    @timb00 Před 2 lety +1

    Thanks man, finally got it!

  • @strandloper
    @strandloper Před 3 lety +1

    Thanks, that's a nice clear explanation.

  • @distinguishedmoments2277
    @distinguishedmoments2277 Před 2 lety +1

    I love your videos mate! Thanks a lot

  • @adnanmaqboolkhan7522
    @adnanmaqboolkhan7522 Před rokem

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

  • @christianf7740
    @christianf7740 Před 2 lety +1

    This is great stuff.

  • @ievheniiierokhin1677
    @ievheniiierokhin1677 Před 3 lety +1

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

  • @mahesh_rcb
    @mahesh_rcb Před 3 lety +3

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

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

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

  • @peternguyen9382
    @peternguyen9382 Před rokem

    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.

  • @CleberCarvalhoTI
    @CleberCarvalhoTI Před 2 lety +1

    Ottima spiegazione.

  • @shreyasacharya
    @shreyasacharya Před 2 lety +1

    Awesome!

  • @milos5247
    @milos5247 Před rokem

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

  • @kiranshetty8342
    @kiranshetty8342 Před 2 lety

    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  Před 2 lety +1

      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.

  • @coolfyb
    @coolfyb Před rokem +1

    eXcellently explained.

  • @joakimcarlsson7826
    @joakimcarlsson7826 Před 3 lety +1

    Would love an explanation around yield return

  • @Jarenaut
    @Jarenaut Před 3 lety

    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  Před 3 lety +1

      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.

  • @karsten600
    @karsten600 Před 2 lety +1

    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?

  • @andreapellegrini2794
    @andreapellegrini2794 Před 3 lety +1

    Thanks you man

  • @marvinalone
    @marvinalone Před 2 lety

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

  • @MarvinKleinMusic
    @MarvinKleinMusic Před 3 lety

    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  Před 3 lety

      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 Před 3 lety

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

  • @Kumar-yn4bs
    @Kumar-yn4bs Před 2 lety

    Make a sample code of application using Ivaluetaskasync any example please

  • @tomnolane
    @tomnolane Před 2 lety +1

    thanks

  • @randompoints
    @randompoints Před 3 lety

    Can we consider ValueTask for singleton service method?

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +1

      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 Před rokem

    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  Před rokem

      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
    @philippelhaus Před 3 lety

    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  Před 3 lety

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

  • @Rob_III
    @Rob_III Před 3 lety

    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  Před 3 lety +1

      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  Před 3 lety +1

      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 Před 3 lety +1

      @@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 Před 3 lety +1

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

    • @ronaldmackee3401
      @ronaldmackee3401 Před 3 lety

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

  • @imixal
    @imixal Před 2 lety

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

    • @BrianLagunas
      @BrianLagunas  Před 2 lety +1

      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

  • @DickBakerSql
    @DickBakerSql Před rokem

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