ValueTask vs Task in C#
Imagine a method that does an asynchronous job just for one time or 1% and in 99% does a synchronous job.
For example: we have a method which for the first time reads a value from a file on a disc asynchronously, then if you call it again it will return the same value.
private static string _myInformation;
public async ValueTask<string> GetInformation()
{
if (_myInformation is null)
{
_myInformation = await _myFileService.ReadInformation();
}
return _myInformation;
}
It is a good scenario that you can use ValueTask instead of Task.
As you know Task is a reference type and it is allocated on the heap but on the contrary, ValueTask is a value type and it is initialized on the stack so it would make a better performance in this scenario.
Senior Solution Architect
2 年Isn't ReadInformation() a Task anyway?
.NET Senior Software Engineer at BGSW
2 年Good Information. Thank Ehsan ??