如何AsyncLocal的语义从逻辑调用上下文有什么不同? [英] How do the semantics of AsyncLocal differ from the logical call context?

查看:1473
本文介绍了如何AsyncLocal的语义从逻辑调用上下文有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET 4.6引入了 AsyncLocal< T> 类沿控制的异步流流动环境中的数据。我有previously使用 CallContext.LogicalGet / SetData的为此,我想知道是否和在哪些方面两者是语义不同(除了显而易见的API差异像强类型和缺乏依赖于字符串键)。

.NET 4.6 introduces the AsyncLocal<T> class for flowing ambient data along the asynchronous flow of control. I've previously used CallContext.LogicalGet/SetData for this purpose, and I'm wondering if and in what ways the two are semantically different (beyond the obvious API differences like strong typing and lack of reliance on string keys).

推荐答案

语义是pretty大同小异。两者都存储在的ExecutionContext 和流经异步调用。

The semantics are pretty much the same. Both are stored in the ExecutionContext and flow through async calls.

的差别是API的变化(就像你描述的)与注册一个回调值变化的能力在一起。

The differences are API changes (just as you described) together with the ability to register a callback for value changes.

从技术上讲,有在实施的 CallContext中每次复制时(使用克隆 CallContext.Clone ),而 AsyncLocal 的数据保存在 ExecutionContext._localValues​​ 字典,只是引用被复制在没有任何额外的工作。

Technically, there's a big difference in the implementation as the CallContext is cloned each time it is copied (using CallContext.Clone) while the AsyncLocal's data is kept in the ExecutionContext._localValues dictionary and just that reference is copied over without any extra work.

若要当你改变一个新的字典创建 AsyncLocal 的价值和所有现有的值是浅拷贝到新确定的更新只影响当前流之一。

To make sure updates only affect the current flow when you change the AsyncLocal's value a new dictionary is created and all the existing values are shallow-copied to the new one.

这差别可能有好有坏的表现,具体情况取决于 AsyncLocal 被使用。

That difference can be both good and bad for performance, depending on where the AsyncLocal is used.

现在,汉斯·帕桑特在评论中提到 CallContext中最初是为远程制作,并在远程不支持(如净核心)不可用这这也许就是为什么 AsyncLocal 添加到框架:

Now, as Hans Passant mentioned in the comments CallContext was originally made for remoting, and isn't available where remoting isn't supported (e.g. .Net Core) which is probably why AsyncLocal was added to the framework:

#if FEATURE_REMOTING
    public LogicalCallContext.Reader LogicalCallContext 
    {
        [SecurityCritical]
        get { return new LogicalCallContext.Reader(IsNull ? null : m_ec.LogicalCallContext); } 
    }

    public IllogicalCallContext.Reader IllogicalCallContext 
    {
        [SecurityCritical]
        get { return new IllogicalCallContext.Reader(IsNull ? null : m_ec.IllogicalCallContext); } 
    }
#endif


请注意:这里还有一个 AsyncLocal 在Visual Studio SDK,基本上是在 CallContext中的包装展示了如何类似的概念是: System.Threading.AsyncLocal


Note: there's also an AsyncLocal in the Visual Studio SDK that is basically a wrapper over CallContext which shows how similar the concepts are: System.Threading.AsyncLocal.

这篇关于如何AsyncLocal的语义从逻辑调用上下文有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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