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”:
Sponsor Me on GitHub:
Get 2 Free Stocks on WeBull (Valued up to $1600 when you deposit $100)
🐦 Twitter: http://bit.ly/BrianLagunasOnTwitter