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;
}

Re: ThreadStatic attribute by Jon

Jon
Wed May 07 05:12:57 CDT 2008

On May 7, 10:23 am, CJ <cj_junkt...@mail.com> wrote:
> 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

Re: ThreadStatic attribute by CJ

CJ
Thu May 08 06:28:58 CDT 2008

On May 7, 12:12 pm, "Jon Skeet [C# MVP]" <sk...@pobox.com> wrote:
> On May 7, 10:23 am, CJ <cj_junkt...@mail.com> wrote:
>
>
>
> > 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!