OneStopTesting.com - Testing EBooks, Tutorials, Articles, Jobs, Training Institutes etc.
OneStopGate.com - Gate EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopMBA.com - MBA EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopIAS.com - IAS EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopSAP.com - SAP EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopGRE.com - of GRE EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
Thread- local storage of data in .NET | Articles | Recent Articles | News Article | Interesting Articles | Technology Articles | Articles On Education | Articles On Corporate | Company Articles | College Articles | Articles on Recession
Home » Articles » Thread- local storage of data in .NET
Thread- local storage of data in .NET
Article Posted On Date : Thursday, March 22, 2012
Thread- local storage of data in .NET
Advertisements
Introduction Suppose you're writing a multi-threaded application and you want each thread to have its own copy of some data. You also want this data to persist throughout the lifetime of the thread. As each thread has its own stack, it also has its own copy of any local variables. However, the trouble with these is that they are not persistent - once the current method has finished executing they're destroyed. Also local variables are scoped to the current method and so, if you want them to be available to other methods which the current method calls, then you need to pass them as parameters. This can get rather messy if there are several such variables and multiple method calls. You could use a static field to store persistent data but then there's only one copy of the data which all threads share. So is there anything you can use so that each thread has its own copy of persistent data? The answer is Thread-Local Storage or TLS for short. There are three ways to create TLS using a .NET application each of which is discussed in turn below. The ThreadStatic attribute If you decorate a static field with the ThreadStatic attribute, then each thread will have its own copy of that field. Here's an example: using System; using System.Threading; class ThreadStaticTest { [ThreadStatic] static string greeting; static void Main() { greeting = "Goodbye from the main thread"; Thread t = new Thread(ThreadMethod); t.Start(); t.Join(); Console.WriteLine(greeting); // prints the main thread's copy Console.ReadKey(); } static void ThreadMethod() { greeting = "Hello from the second thread"; // only affects the second thread's copy Console.WriteLine(greeting); } }
Amazon.in Widgets