Introduction:- In c# language Threadstatic is used when we work with threading. Threadstatic is a keyword which is used to declare static...
Introduction:-
In c# language Threadstatic is used when we work with threading. Threadstatic is a keyword which is used to declare static resource.
What is static resources ?
Static resource means the resource is specific to each thread.
For example:- You have two thread and if both the thread using same resource at that time the resource not sharable it specific to each thread.
Background :-
Let's have a Demo using static thread :-
class ThreadStatic
{
[ThreadStatic]
static int _iField;
public static void Main()
{
Thread t = new Thread(new ThreadStart(() =>
{
for (int i = 0; i < 10; i++) { _iField++; Console.WriteLine("Thread is {0}",_iField); } })); t.Start(); Thread t1 = new Thread(new ThreadStart(() =>
{
for (int i = 0; i < 10; i++)
{
_iField++;
Console.WriteLine("Second thread is {0}", _iField);
}
}));
t1.Start();
}
}
Output:-
Explanation :- In the above example we have use Threadstatic keyword for _ifield variable so when we executing two different thread then each thread have a copy of _iField variable; due to this reason our output is 1-10 in each thread.
But if i remove the ThreadStatic form the _ifiled variable then we get the out put as 1-20. See bellow :-
Hope you got Now !!!