Overview Of ThreadStatic Attribute In C#

In this article, we will look into C# ThreadStaticAttribute which indicates that the value of a static field is unique for each thread. Marking a static field with this attribute, does not share it among threads and each thread will have its own copy of the field. So, changing the value on one thread will not affect it on another thread. We can apply this attribute to static fields only, and cannot apply it on properties.

Let’s understand it with the following code in a console application:

code

Here, I have created two variables - one is static and another one is ThreadStatic. Let’s run it:

output

As we can see, static variable is shared among threads whereas ThreadStatic variable is unique to each thread and not shared.

We don’t require to specify the initial values for the fields marked with ThreadStaticAttribute, because such initialization occurs only once when the class constructor executes, therefore, it affects only one thread. If you do not specify an initial value, you can rely on the field being initialized to its default value, if it is a value type. The value will be null if it is a reference type.

code

Here, we initialized ThreadStatic field with 10. When we run it, only the main (first) thread’s field will be having 10. All the rest of the threads will have a default value of 0.

Output

Output

We can use ThreadLocal<T> which is similar to ThreadStatic. But, it allows us to pass initializer function to set its value for every thread instead of the first thread only.

As an overview, we can mark a static field with ThreadStaticAttribute which will not share it among threads. Each executing thread will have a separate instance of the field, and independently sets and gets values for that field. If the field is accessed on a different thread, it will contain a different value. In addition to applying the ThreadStaticAttribute attribute to a field, you must also define it as a static field.

For more details on this issue, please refer here.

I am ending the things here. I hope this article will be helpful for all.

Up Next
    Ebook Download
    View all
    Learn
    View all