首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么AsyncLocal与CallContext不同

为什么AsyncLocal与CallContext不同
EN

Stack Overflow用户
提问于 2017-01-24 10:10:40
回答 1查看 2.4K关注 0票数 1

运行下面的代码,您可以看到CallContext和AsyncLocal之间有不同之处。

代码语言:javascript
复制
using System;
using System.Runtime.Remoting.Messaging;
using System.Threading;

namespace AsyncLocalIsDifferentThanCallContext
{
    class Program
    {
        public static AsyncLocal<int> AsyncLocal = new AsyncLocal<int>();

        public static int CallContextValue
        {
            get
            {
                var data = CallContext.GetData("CallContextValue");
                if (data == null)
                    return 0;
                return (int) data;
            }
            set { CallContext.SetData("CallContextValue", value); }
        }

        static void Main(string[] args)
        {
            AsyncLocal.Value = 1;
            CallContextValue = 1;
            new Thread(() =>
            {
                Console.WriteLine("From thread AsyncLocal: " + AsyncLocal.Value); // Should be 0 but is 1
                Console.WriteLine("From thread CallContext: " + CallContextValue); // Value is 0, as it should be
            }).Start();
            Console.WriteLine("Main AsyncLocal: " + AsyncLocal.Value);
            Console.WriteLine("Main CallContext: " + CallContextValue);
        }
    }
}

你能解释一下为什么吗?

我预计每个线程的AsyncLocal值都是唯一的,因为文档说它应该运行,而CallContext则是这样做的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-24 13:35:51

你认为ThreadLocalAsyncLocal可以像它所说的那样在线程间流动。

由于基于任务的异步编程模型倾向于抽象线程的使用,所以AsyncLocal实例可以用于跨线程的持久化数据()。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41825375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档