Reputation: 329
If you set the ThreadStatic
flag on a static field, each thread that runs would have a separate variable, so if you have a static int
field and a method that just increments its value 5 times starting that method on two separate threads will just give you two separate ints with a value of 5, instead of one with a value of 10.
In that case, what is the difference between this approach and having a non-static field that gets instantiated for every thread?
Upvotes: 1
Views: 313
Reputation: 1500903
ThreadStaticAttribute
is decorated with:
[AttributeUsageAttribute(AttributeTargets.Field, Inherited = false)]
So you can't apply it to methods, only fields. Each thread effectively has an independent variable corresponding to that field. But it can only be applied to static fields - you can't have "per instance and per thread" fields, which is what you'd effectively be asking for.
Now yes, if you're in sufficient control of the threads that are running the code that you're able to create a separate object for each thread, and use an instance field instead, then yes, that's a perfectly fine alternative to ThreadStatic
. However, that's not always the situation you're in. Sometimes you need to write code which is safe to call from multiple threads, but isn't nicely partitioned into a separate object per thread. ThreadStatic
is useful for that.
Having said that, I'd generally use ThreadLocal<T>
instead of ThreadStatic
as an alternative approach to having per-thread data.
As a side note, you can't have a static variable within a method. You can only declare local variables within methods, and they're neither static fields nor instance fields - they're just local variables. You can have a static field that happens to only be used within a single method, but that's not the same as declaring the variable within the method.
Upvotes: 2