C#--线程本地化存储

      有时以单个线程为基础存储信息比较方便,所存储的信息只对该线程有用,这叫做线程本地化存储。通常用Thread对象的AllocateNamedDataSlot方法创建存储名,用GetData取出内容,最后用FreeNamedDataSlot释放。

     

1 /*
2 Example14_4.cs illustrates the use of thread-local storage
3 */
4
5 using System;
6 using System.Threading;
7
8 class Example14_4
9 {
10
11 // the WriteError method writes error info from the current thread
12 public static void WriteError()
13 {
14 Console.WriteLine("Error number = " + Thread.GetData(Thread.GetNamedDataSlot("ErrNo")));
15 Console.WriteLine("Error source = " + Thread.GetData(Thread.GetNamedDataSlot("ErrSource")));
16 }
17
18 // the SetError method sets a random error number
19 public static void SetError()
20 {
21 Random r = new Random();
22 Thread.SetData(Thread.GetNamedDataSlot("ErrNo"), r.Next(100));
23 Thread.SetData(Thread.GetNamedDataSlot("ErrSource") ,Thread.CurrentThread.Name);
24 WriteError();
25 }
26
27 public static void Main()
28 {
29 // allocate some named data slots
30 Thread.AllocateNamedDataSlot("ErrNo");
31 Thread.AllocateNamedDataSlot("ErrSource");
32
33 // create and start a second thread
34 Thread t2 = new Thread(new ThreadStart(SetError));
35 t2.Name = "t2";
36 t2.Start();
37
38 // create a third thread
39 Thread t3 = new Thread(new ThreadStart(SetError));
40 t3.Name = "t3";
41 t3.Start();
42
43 // clean up the data slots
44 Thread.FreeNamedDataSlot("ErrNo");
45 Thread.FreeNamedDataSlot("ErrSource");
46
47 }
48
49 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值