Should I await ValueTask<T>?

那年仲夏 提交于 2019-12-07 16:32:53

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/52425028/should-i-await-valuetaskt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!