{"id":1559,"date":"2014-02-27T20:46:46","date_gmt":"2014-02-27T20:46:46","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=1559"},"modified":"2014-02-27T20:46:46","modified_gmt":"2014-02-27T20:46:46","slug":"using-threadstatic-and-threadlocal","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/using-threadstatic-and-threadlocal\/","title":{"rendered":"Using ThreadStatic and ThreadLocal"},"content":{"rendered":"<p>First off these are two different objects altogether, ThreadStatic is actually ThreadStaticAttribute and you mark a static variable with the attribute. Whereas ThreadLocal is a generic class.<\/p>\n<p><strong>So why are we looking at both in the one post?<\/strong><\/p>\n<p>Both ThreadStatic and ThreadLocal are used to allow us to declare thread specific values\/variables. <\/p>\n<p><strong>ThreadStatic<\/strong><\/p>\n<p>A static variable marked with the ThreadStatic attribute is not shared between threads, therefore each thread gets it&#8217;s own instance of the static variable.<\/p>\n<p>Let&#8217;s look at some code<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n&#x5B;ThreadStatic]\r\nstatic int value;\r\n\r\nstatic void Main()\r\n{\r\n   Task t1 = Task.Run(() =&gt;\r\n   {\r\n      value++;\r\n      Console.WriteLine(&quot;T1: &quot; + value);\r\n   });\r\n   Task t2 = Task.Run(() =&gt;\r\n   {\r\n      value++;\r\n      Console.WriteLine(&quot;T2: &quot; + value);\r\n   });\r\n   Task t3 = Task.Run(() =&gt;\r\n   {\r\n      value++;\r\n      Console.WriteLine(&quot;T3: &quot; + value);\r\n   });\r\n\r\n   Task.WaitAll(t1, t2, t3);\r\n}\r\n<\/pre>\n<p>The output from this (obviously the ordering may be different) is<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nT3: 1\r\nT1: 1\r\nT2: 1\r\n<\/pre>\n<p>One thing to watch out for is that if we initialize the ThreadStatic variable, for example if we write the following<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n&#x5B;ThreadStatic]\r\nstatic int value = 10;\r\n<\/pre>\n<p>you need to be aware that this <string>is<\/strong> initialized only on the thread it&#8217;s declared on, all the threads which use <\/em>value<\/em> will get a variable initialised with it&#8217;s default value, i.e. 0.<\/p>\n<p>For example, if we change the code very slightly to get<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n&#x5B;ThreadStatic]\r\nstatic int value = 10;\r\n\r\nstatic void Main()\r\n{\r\n   Task t1 = Task.Run(() =&gt;\r\n   {\r\n      value++;\r\n      Console.WriteLine(&quot;T1: &quot; + value);\r\n   });\r\n   Task t2 = Task.Run(() =&gt;\r\n   {\r\n      value++;\r\n      Console.WriteLine(&quot;T2: &quot; + value);\r\n   });\r\n   Task t3 = Task.Run(() =&gt;\r\n   {\r\n      value++;\r\n      Console.WriteLine(&quot;T3: &quot; + value);\r\n   });\r\n\r\n   Console.WriteLine(&quot;Main thread: &quot; + value);\r\n   \r\n   Task.WaitAll(t1, t2, t3);\r\n}\r\n<\/pre>\n<p>The output will look something like<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\nMain thread: 10\r\nT2: 1\r\nT1: 1\r\nT3: 1\r\n<\/pre>\n<p>Finally as, by definition each variable is per thread, operations upon the instance of the variable are thread safe.<\/p>\n<p><strong>ThreadLocal<\/strong><\/p>\n<p>Like the ThreadStatic attribute, the ThreadLocal class allows us to declare a variable which is not shared between threads, one of the extra capabilities of this class is that we can initialize each instance of the variable as the class the supplied factory method to create and\/or initialize the value to be returned. Also, unlike ThreadStatic which only works on static fields, ThreadLocal can be applied to static or instance variables.<\/p>\n<p>Let&#8217;s look at the code<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nstatic void Main()\r\n{\r\n   ThreadLocal&lt;int&gt; local = new ThreadLocal&lt;int&gt;(() =&gt;\r\n   {\r\n      return 10;\r\n   });\r\n\r\n   Task t1 = Task.Run(() =&gt;\r\n   {\r\n      local.Value++;\r\n      Console.WriteLine(&quot;T1: &quot; + local.Value);\r\n   });\r\n   Task t2 = Task.Run(() =&gt;\r\n   {\r\n      local.Value++;\r\n      Console.WriteLine(&quot;T2: &quot; + local.Value);\r\n   });\r\n   Task t3 = Task.Run(() =&gt;\r\n   {\r\n      local.Value++;\r\n      Console.WriteLine(&quot;T3: &quot; + local.Value);\r\n   });\r\n\r\n   Task.WaitAll(t1, t2, t3);\r\n   local.Dispose();\r\n}\r\n<\/pre>\n<p>The output order may be different, but the output will read something like<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\nT2: 11\r\nT3: 11\r\nT1: 11\r\n<\/pre>\n<p>As you can see, each thread altered their own instance of the thread local variable and more over we were able to set the default value to <em>10<\/em>. <\/p>\n<p>The ThreadLocal class implements IDisposable, so we should Dispose of it when we&#8217;ve finished with it.<\/p>\n<p>Apart from Dispose all methods and protected members are thread safe.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>First off these are two different objects altogether, ThreadStatic is actually ThreadStaticAttribute and you mark a static variable with the attribute. Whereas ThreadLocal is a generic class. So why are we looking at both in the one post? Both ThreadStatic and ThreadLocal are used to allow us to declare thread specific values\/variables. ThreadStatic A static [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[3,51],"tags":[],"class_list":["post-1559","post","type-post","status-publish","format-standard","hentry","category-c","category-multi-threading"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/1559","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=1559"}],"version-history":[{"count":13,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/1559\/revisions"}],"predecessor-version":[{"id":1572,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/1559\/revisions\/1572"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=1559"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=1559"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=1559"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}