ThreadStatic is a super-cool concept if you have a static variable. you can make it static "per-thread" by placing the attribute on top. This is one easy way to get around the thread-safety issues of working with statics - as they are per-thread, you do not have to take a lock when updating them.
[ThreadStatic]
private static string Foo;
Here each thread accessing this field will have its own copy and is not visible to other threads.
Initialization => The initial value of thread static field is only applicable to the first accessing thread. And for all the subsequent threads it will be initialized to null.
class Program
{
static void Main(string[] args)
{
Thread th = new Thread(new ThreadStart( ThreadFun ));
Console.WriteLine("writing from main " + Demo.foo);
th.Start();
th.Join();
Console.WriteLine("writing from main " + Demo.foo);
Console.Read();
}
public static void ThreadFun( )
{
Console.WriteLine("writing from thread " + Demo.foo);
Demo.foo= 500;
Console.WriteLine("writing from thread " + Demo.foo);
}
}
public class Demo
{
[ThreadStatic]
public static int foo = 100;
}Output looks like below:
You can see that main thread will get foo value as 100, but the next thread will gets its own seperate static varibale and the initial value as zero..........
*Note : I just tried the same attribute for non static fields, I can see that compiler wont give you any warnings/errors, but no impact.
No comments:
Post a Comment