线程 数据槽
public static CSContext Current
{
get
{
LocalDataStoreSlot storeSlot = GetSlot();
CSContext context = Thread.GetData(storeSlot) as CSContext;
if (context == null)
{
HttpContext httpContext = HttpContext.Current;
if(httpContext == null)
throw new Exception("No CSContext exists in the Current Application. AutoCreate fails since HttpContext.Current is not accessible");
context = new CSContext(httpContext);
SaveContextToStore(storeSlot,context);
}
return context;
}
}
{
get
{
LocalDataStoreSlot storeSlot = GetSlot();
CSContext context = Thread.GetData(storeSlot) as CSContext;
if (context == null)
{
HttpContext httpContext = HttpContext.Current;
if(httpContext == null)
throw new Exception("No CSContext exists in the Current Application. AutoCreate fails since HttpContext.Current is not accessible");
context = new CSContext(httpContext);
SaveContextToStore(storeSlot,context);
}
return context;
}
}
看了上面的这段代码,知道线程有个本地数据槽的概念,这个东西到底有什么作用,是用在单线程里还是多线程里?
相关文章:
线程局部存储(TLS)
存放局部存储步骤:
1、申请数据槽
LocalDataStoreSlot slot = Thread.GetNamedDataSlot("para");
如果不存在名为para的数据槽,将分配一个所有线程均可用的para数据槽
2、往数据槽存放数据
MyPara para = new MyPara();
para.I = i;
Thread.SetData(slot,para);
para.I = i;
Thread.SetData(slot,para);
3、如有必要,释放数据槽
Thread.FreeNamedDataSlot("para");
释放数据槽要小心,该操作将使所有线程存放在被释放的数据槽中的数据丢失。
读取局部存储步骤:
1、根据名字子线程局部存储中获取特定的数据槽
LocalDataStoreSlot slot = Thread.GetNamedDataSlot("para");
2、从数据槽获取数据
Object o = Thread.GetData(slot);
if (o != null)
{
//转化为特定类型
MyPara para = (MyPara) o ;
//.
}
if (o != null)
{
//转化为特定类型
MyPara para = (MyPara) o ;
//.
}