ThreadStatic
標記為 ThreadStaticAttribute 的靜態(在 Visual Basic 中為 Shared)字段不在線程之間共享。每個執行線程都有單獨的字段實例,並且獨立地設置及獲取該字段的值。如果在不同的線程中訪問該字段,則該字段將包含不同的值。注意 不要為標記為 ThreadStaticAttribute 的字段指定初始值,因為這樣的初始化隻會發生一次,因此在類構造函數執行時隻會影響一個線程。在不指定初始值的情況下,如果它是值類型,可依賴初始化為其默認值的字段,如果它是引用類型,則可依賴初始化為空引用(Visual Basic 中為 Nothing)的字段。
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();
}
}
{
[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();
}
}
最後更新:2017-04-02 00:06:29