C# - Return Task<T> or ValueTask<T> if result might be know beforehand?

1.6k Views Asked by At

Take a look at this code:

public async Task<int> GetResult(string param1)
{
    if(param1 == "abc")
       return _knownResult;
    else
       return await LongDatabaseCall();
}

Given that LogDatabaseCall will return a Task<int>, which might be saved into _knownResult, what should be the type of _knownResultTask<int> or ValueTask<int>, performance-wise?

3

There are 3 best solutions below

2
On

The main issue here is regarding allocation and performance.

That's almost never the main issue, actually.

When determining whether you should use Task<T> or ValueTask<T>, the main issue is one of developer training: if everyone on your team is familiar with the pitfalls of ValueTask<T>, then I'd recommend that. However, if not all the coders are familiar with ValueTask<T> (which seems to be true in the general case right now), then I'd recommend Task<T>.

The performance aspects are almost always immaterial.

0
On

You can use Task.FromResult.

return Task.FromResult(knownResult);
3
On

If you know result already, it means that there is no IO call or required to wait but other part of your method required await.

For clarity I assume that you want to return value 1 for first condition.

// 1. If knownresult is type of Task<int> then   

   public async Task<int> GetResult(string param1)
   {
    if(param1 == "abc")
       return await knownResult;
    else
       return await LongDatabaseCall();
   }
  1. If knownResult is int then (no await)

    public async Task<int> GetResult(string param1)
     {
         if(param1 == "abc")
            return knownResult;
         else
            return await LongDatabaseCall();
     }