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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With