What is Thread static attribute in c#
the thread calls its own call stack that stores all methods are executed, local variables are stored on the call stack and private to the thread.
A thread can also have its own data that's not a local variable, By making a field with static attribute, each thread makes its Own copy of field
class Program
{
[ThreadStatic] // remove and chek
public static int _field;
static void Main(string[] args)
{
// threastatic attribute
new Thread(() =>
{
for (int i = 0; i < 10; i++)
{
_field++;
Console.WriteLine("Thread A:{0}", _field);
}
}).Start();
new Thread(() =>
{
for (int i = 0; i < 10; i++)
{
_field++;
Console.WriteLine("Thread B: {0}",_field);
}
}).Start();
Console.ReadKey();
}
}
A thread can also have its own data that's not a local variable, By making a field with static attribute, each thread makes its Own copy of field
class Program
{
[ThreadStatic] // remove and chek
public static int _field;
static void Main(string[] args)
{
// threastatic attribute
new Thread(() =>
{
for (int i = 0; i < 10; i++)
{
_field++;
Console.WriteLine("Thread A:{0}", _field);
}
}).Start();
new Thread(() =>
{
for (int i = 0; i < 10; i++)
{
_field++;
Console.WriteLine("Thread B: {0}",_field);
}
}).Start();
Console.ReadKey();
}
}
No comments