ValueTask vs Task

First of all, let me say that ValueTask was introduced in C# for a very specific scenario, when a method can return a result either synchronously or asynchronously. For example, let’s imagine a method with a few execution paths: using an "if" or a "switch" statement (it really doesn’t matter). At least one execution path must return the result synchronously (for example, a cached value or a constant returned due to business logic or validation failure). And, of course, there should also be an execution path that returns the result asynchronously (for example, from a network call or a service, etc.). For example:

Example of the method


In most cases, the cache exists, and because of this, the synchronous part of the code is executed. And this is where ValueTask comes into play.

Back