阻止线程上下文流动

 1         /// <summary>
 2         /// 阻止执行上下文流动来影响线程逻辑调用上下文数据
 3         /// </summary>
 4         public static void FlowDataContext()
 5         {
 6             //将数据放到FlowDataContext线程的逻辑调用上下文
 7             CallContext.LogicalSetData("key", "FlowData");
 8 
 9             //初始化要由一个线程池线程做的工作
10             //线程池线程能访问逻辑调用上下文数据
11             ThreadPool.QueueUserWorkItem(state => Console.WriteLine("1.key:{0}", CallContext.LogicalGetData("key")));
12 
13             //阻止FlowDataContext线程的执行上下文流动
14             ExecutionContext.SuppressFlow();
15 
16             //初始化要由一个线程池线程做的工作
17             //线程池线程不能访问逻辑调用上下文数据
18             ThreadPool.QueueUserWorkItem(state => Console.WriteLine("2.key:{0}", CallContext.LogicalGetData("key")));
19 
20             //恢复FlowDataContext线程的执行上下文流动
21             ExecutionContext.RestoreFlow();
22 
23             ThreadPool.QueueUserWorkItem(state => Console.WriteLine("3.key:{0}", CallContext.LogicalGetData("key")));
24         }

 

posted on 2018-05-12 11:19  庭前花满留晚照  阅读(218)  评论(0编辑  收藏  举报

导航