ThreadStatic in C#

Introduction:-

In c# language Threadstatic is used when we work with threading. Threadstatic is a keyword which is used to declare static resource.

What is static resources ?

Static resource means the resource is specific to each thread.
For example:- You have two thread and if both the thread using same resource at that time the resource not sharable it specific to each thread.

Background :-
Let’s have a Demo using static thread :-

class ThreadStatic
    {
        [ThreadStatic]
        static int _iField;
        public static void Main()
        {
            Thread t = new Thread(new ThreadStart(() =>
              {
                  for (int i = 0; i < 10; i++) { _iField++; Console.WriteLine("Thread is {0}",_iField); } })); t.Start(); Thread t1 = new Thread(new ThreadStart(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    _iField++;
                    Console.WriteLine("Second thread is {0}", _iField);
                }
            }));
            t1.Start();
        }
    }

Output:-
threadstatic

Explanation :- In the above example we have use Threadstatic keyword for _ifield variable so when we executing two different thread then each thread have a copy of _iField variable; due to this reason our output is 1-10 in each thread.

But if i remove the ThreadStatic form the _ifiled variable then we get the out put as 1-20. See bellow :-

threadstatic

Hope you got Now !!!

#Share#Like#Comment

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s