【多线程笔记】线程的本地存储

实现线程的本地存储,也就是线程内可见。这些数据都是存放在线程环境块中,是线程的空间开销

有以下几种方式

线程数据槽

已过时,建议使用ThreadStaticAttribute

static void Main(string[] args)
{
  var slot = Thread.AllocateDataSlot();//给所有线程分配一个数据槽,存放数据。。。

  Thread.SetData(slot, "helloworld");//当前线程设置数据,只有当前线程可读数据

  Console.WriteLine(Thread.GetData(slot));//helloworld

  var t1 = new Thread(() => {
    Console.WriteLine("t1:"+Thread.GetData(slot));//无数据
  });

  t1.Start();
  Console.ReadKey();
}

ThreadStaticAttribute

比数据槽性能好,使用方便

[ThreadStatic]
static string username = string.Empty;

ThreadLocal

也是用来做 线程可见性,它是强类型的

static void Main(string[] args)
{
  ThreadLocal<string> local = new ThreadLocal<string>();
  local.Value = "hello world!!!";
  var t = new Thread(() =>
  {
    Console.WriteLine("当前工作线程:{0}", local.Value);
  });
  t.Start();
  Console.WriteLine("主线程:{0}", local.Value);
  Console.Read();
}

CallContext

线程内可见。当 CallContext 沿执行代码路径往返传播并且由该路径中的各个对象检查时,可将对象添加到其中。
使用场景:当对象需要线程内全局使用。Core不支持

CallContext.SetData(key, temp);
DbContext temp = CallContext.GetData(key) as DbContext;
posted @ 2020-05-25 15:39  .Neterr  阅读(479)  评论(1编辑  收藏  举报