Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I await ValueTask<T>?

Which would be a valid implementation of ValueTask please? Cache service returns data either from cache or DB.

public async ValueTask<IList<HrEmploymentDataCustom>> GetEmployeesFacts()
{
    try
    {
        var facts = (List<HrEmploymentDataCustom>) _memoryCache.Get("facts");
        return facts ?? await _accountService.GetEmploymentFacts(DetailsRequestType.All, null);
    }
    catch (Exception e)
    {
        var tc = new TelemetryClient();
        tc.TrackException(e);
        return null;
    }
}

Would this be: var employeesFacts = await _cacheService.GetEmployeesFacts();

or var employeesFacts = _cacheService.GetEmployeesFacts().Result;

Little bit confused here.

like image 322
sziszu Avatar asked Sep 20 '18 12:09

sziszu


1 Answers

Would this be:

var employeesFacts = await _cacheService.GetEmployeesFacts();

Typically yes.

or

var employeesFacts = _cacheService.GetEmployeesFacts().Result;

Little bit confused here.

NEVER EVER.

Let's unconfuse you.

First: value task is simply a task that is copied by value instead of reference. Do not use ValueTask unless you know the difference and have a reason to do so driven by an empirical performance study that indicates that regular tasks are a large contributor to collection pressure. Just use regular tasks almost all the time.

You don't change how you use a task based on whether it was copied by value or by reference. You await tasks, regardless.

You never use .Result on a task, regardless of whether it is a value or a reference. Why? Because suppose the task is not complete: then Result will wait synchronously for its completion. Suppose the final step of the workflow is currently in the queue of the current thread waiting to be dispatched. You just put that thread to sleep! Now the thread is sleeping, waiting for itself to wake it up, and so it will sleep forever. Never use .Result. It's the wrong thing to do almost always.

like image 56
Eric Lippert Avatar answered Oct 30 '22 08:10

Eric Lippert