ThreadStatic attribute

C

CJ

I came across the ThreadStatic attribute today, but I'm a bit confused
by it.

I understand that it makes a variable static to a particular thread,
so each thread will have it's own value for it (unlike a regular
static variable). But then what makes it different to just an
ordinary class level variable? In other words, what's the difference
between var1 and var2 below?

public class Test
{
[ThreadStatic]
public static int var1;

public int var2;
}
 
J

Jon Skeet [C# MVP]

I came across the ThreadStatic attribute today, but I'm a bit confused
by it.

I understand that it makes a variable static to a particular thread,
so each thread will have it's own value for it (unlike a regular
static variable). But then what makes it different to just an
ordinary class level variable? In other words, what's the difference
between var1 and var2 below?

public class Test
{
[ThreadStatic]
public static int var1;

public int var2;

}

Ordinary variables are shared between threads. So, if thread X sets
values for var1 and var2, and thread Y reads them, it will see the new
value for var2, but not the new value for var1.

Jon
 
C

CJ

I came across the ThreadStatic attribute today, but I'm a bit confused
by it.
I understand that it makes a variable static to a particular thread,
so each thread will have it's own value for it (unlike a regular
static variable). But then what makes it different to just an
ordinary class level variable? In other words, what's the difference
between var1 and var2 below?
public class Test
{
[ThreadStatic]
public static int var1;
public int var2;

Ordinary variables are shared between threads. So, if thread X sets
values for var1 and var2, and thread Y reads them, it will see the new
value for var2, but not the new value for var1.

Jon

Doh! I realised the answer this morning as I woke up :) Clearly I
wasn't thinking yesterday!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top