有时以单个线程为基础存储信息比较方便,所存储的信息只对该线程有用,这叫做线程本地化存储。通常用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 }