[Quote=引用 1 楼 newegg2009 的回复:]
//标记为 ThreadStaticAttribute 的静态字段不在线程之间共享。
// 可以测试以下的实例有助于理解
class Program
{
[ThreadStatic]
static int i;
static Random r = new Random();
public static void ThreadProc()
{
i = r.Next(1, 10);
while (true)
{
Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, i);
Thread.Sleep(500);
}
}
public static void Main()
{
for (int i = 0; i < 2; i++)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Name = "T" + i.ToString();
t.Start();
}
Console.WriteLine("Press Enter key to exit...");
Console.ReadLine();
}
}
//标记为 ThreadStaticAttribute 的静态字段不在线程之间共享。
// 可以测试以下的实例有助于理解
class Program
{
[ThreadStatic]
static int i;
static Random r = new Random();
public static void ThreadProc()
{
i = r.Next(1, 10);
while (true)
{
Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, i);
Thread.Sleep(500);
}
}
public static void Main()
{
for (int i = 0; i < 2; i++)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Name = "T" + i.ToString();
t.Start();
}
Console.WriteLine("Press Enter key to exit...");
Console.ReadLine();
}
}