我应该等待ValueTask< T>吗? [英] Should I await ValueTask<T>?

查看:95
本文介绍了我应该等待ValueTask< T>吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问哪个是ValueTask的有效实现? 缓存服务从缓存或数据库返回数据.

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;
    }
}

会是:var employeesFacts = await _cacheService.GetEmployeesFacts();

var employeesFacts = _cacheService.GetEmployeesFacts().Result;

这里有点困惑.

推荐答案

会是:

var employeesFacts = await _cacheService.GetEmployeesFacts();

通常是.

var employeesFacts = _cacheService.GetEmployeesFacts().Result;

这里有点困惑.

Little bit confused here.

从来没有.

让我们让您感到困惑.

Let's unconfuse you.

首先:值任务只是一个由值(而不是引用)复制的任务. 不要使用ValueTask,除非您知道差异,并有理由进行实证性能研究,表明常规任务是造成收集压力的主要因素,才有理由这样做.几乎一直都在使用常规任务.

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.

永远不要在任务上使用.Result,无论它是值还是引用.为什么?因为假设任务未完成:Result将同步等待其完成. 假设工作流的最后一步当前位于等待分派的当前线程的队列中.您只需要使该线程进入睡眠状态即可!现在线程正在休眠,等待自身唤醒它,因此它将永远休眠.切勿使用.Result.几乎总是做错事了.

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.

这篇关于我应该等待ValueTask&lt; T&gt;吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆