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.


Andrei Kladov

Senior Solution Architect

2 年

Isn't ReadInformation() a Task anyway?

回复
Tuan Huy Dang

.NET Senior Software Engineer at BGSW

2 年

Good Information. Thank Ehsan ??

要查看或添加评论,请登录

Ehsan E.的更多文章

  • CDN ????

    CDN ????

    CDN ???? Content Delivery Network ? ?? ????? ???? ????? ????? ??????. ?? ?? ?? ?? ???????? ????? ?? ?? ???? ?????????…

    1 条评论
  • OpenEHR ?????

    OpenEHR ?????

  • Visual Studio Tips And Tricks

    Visual Studio Tips And Tricks

    In this article, i will cover some tips that will make you, to have better experience of using visual studio. Find…

社区洞察

其他会员也浏览了