A static field marked with ThreadStaticAttribute is not shared between threads. Each executing thread has a separate instance of the field, and independently sets and gets values for that field. If the field is accessed on a different thread, it will contain a different value.
1. ThreadStatic must on top of a static member
2. DO NOT specify the initial value/reference, it won't take effect.
Here is the reference and test code.
http://msdn.microsoft.com/en-us/library/system.threadstaticattribute.aspx
http://blogs.msdn.com/b/jfoscoding/archive/2006/07/18/670497.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class ThreadStaticTest
{
public static void _Main()
{
ThreadStaticTest1 test = new ThreadStaticTest1();
new Thread(new ThreadStart(test.Run)).Start();
Console.ReadLine();
new Thread(new ThreadStart(test.Run)).Start();
Console.ReadLine();
test.wait.Set();
}
}
class ThreadStaticTest1
{
[ThreadStatic]
private static string strTreadStatic="stat";
private static string strNonThreadStatic="nonstat";
public EventWaitHandle wait;
public ThreadStaticTest1()
{
wait = new EventWaitHandle(false, EventResetMode.ManualReset);
}
private void Display()
{
Console.WriteLine("Static: " + strTreadStatic);
Console.WriteLine("Non static: " + strNonThreadStatic);
}
public void Run()
{
Console.WriteLine("Original\r\n===========");
Display();
strTreadStatic = Guid.NewGuid().ToString();
strNonThreadStatic = Guid.NewGuid().ToString();
Console.WriteLine("Changed\r\n============");
Display();
wait.WaitOne();
Console.WriteLine("quit Run");
}
}
}
Original
===========
Static:
Non static: nonstat
Changed
============
Static: 4037bdc9-68e6-4035-b6bb-e9ecc4f9b4e2
Non static: 262a1339-9957-4fe2-9e49-bd0fa9450fcc
Original
===========
Static:
Non static: 262a1339-9957-4fe2-9e49-bd0fa9450fcc
Changed
============
Static: 21c971d8-66df-4eb5-bd7c-a63c50951a3f
Non static: 723b2f9d-9027-41f3-b491-47a027db6102
quit Run
quit Run
Press any key to continue . . .