﻿<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Ayende @ Rahien</title><link>http://ayende.com</link><description>Ayende @ Rahien</description><copyright>Copyright (C) Ayende Rahien  2004 - 2021 (c) 2026</copyright><ttl>60</ttl><item><title>Jonathan Oliver commented on Challenge: Why is this wrong?</title><description>ThreadStatic does not get along well when operating in a web environment because IIS may not necessarily start and end your request on the same thread:
  
  
[www.hanselman.com/.../...pContextCurrentItems.aspx](http://www.hanselman.com/blog/ATaleOfTwoTechniquesTheThreadStaticAttributeAndSystemWebHttpContextCurrentItems.aspx)</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment27</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment27</guid><pubDate>Tue, 20 Oct 2009 02:36:35 GMT</pubDate></item><item><title>Tobin Harris commented on Challenge: Why is this wrong?</title><description>In many cases it's more flexible to use a container for specifying lifecycle, rather than hard coding the desired one-instance-per-thread singleton behaviour. That could allow the component to be adapted and tested in different contexts (web, for example). 
  
  
Other than that, the "subsequent threads will have nulls" problem raised by @qbik is obvioiusly a serious issue :) 
  
  
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment26</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment26</guid><pubDate>Mon, 19 Oct 2009 23:31:06 GMT</pubDate></item><item><title>jocke commented on Challenge: Why is this wrong?</title><description>msdn.microsoft.com/en-us/library/system.threadstaticattribute.aspx
  
"Do not specify initial values for fields marked with because such initialization occurs only once, when the class constructor executes, and therefore 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, or to null if it is a reference typ".
  
  
[http://www.yoda.arachsys.com/csharp/singleton.html](http://www.yoda.arachsys.com/csharp/singleton.html)  
"Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed."
  
  
Personally I think that the semantic fault is the worst, it can't be a singleton if it would (potentially) be initialized one time for each thread accessing it!
  
  
Greetings from sweden /jocke
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment25</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment25</guid><pubDate>Mon, 19 Oct 2009 19:44:40 GMT</pubDate></item><item><title>Josh commented on Challenge: Why is this wrong?</title><description>Just realized I left off my Factory although you should be able to figure I meant it to be:
  
  
public class Factory
  
{
  
        [ThreadStatic]
  
        public static readonly object mySingleton = new object();
  
}
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment24</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment24</guid><pubDate>Mon, 19 Oct 2009 19:20:35 GMT</pubDate></item><item><title>Josh commented on Challenge: Why is this wrong?</title><description>Does this code even compile? 
  
  
By using the Readonly attribute you are saying MySingleton will only be assigned within the field initializer, once that's done it won't be assigned again. 
  
  
Since this field is marked as thread static the field initilizer will only run once when the object is first created. So if you try and access the field from other threads you'd get a null reference exception. 
  
  
Worse yet because its readonly you'd be unable to assign a new value to it.
  
  
Take the following code:
  
  
  
        [MTAThread]
  
        static void Main(string[] args)
  
        {
  
  
            run();
  
  
            Thread t = new Thread(new ThreadStart(run));
  
            t.Start();
  
            t.Join();
  
            Console.Read();
  
  
        }
  
  
  
        static void run()
  
        {
  
  
            if (Factory.mySingleton == null)
  
            {
  
                Console.WriteLine("SingleTon is null");               
  
            }
  
            else
  
            {
  
                Console.WriteLine("Singleton is not null");
  
            }
  
        }
  
  
If you run this you will find it's null when called from a new thread. Now if you try and assign it a value in the run method when it's null, the code will no longer compile because of the read only attribute.
  
  
So you end up with a null field you can only access from a single thread, which would be the thread the static field initalizer ran on.
  
  
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment23</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment23</guid><pubDate>Mon, 19 Oct 2009 19:18:31 GMT</pubDate></item><item><title>Alun Harford commented on Challenge: Why is this wrong?</title><description>This will return null for all threads that didn't call the static initializer (ie. all but one). That's probably not what you wanted.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment22</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment22</guid><pubDate>Mon, 19 Oct 2009 16:12:22 GMT</pubDate></item><item><title>tihobrazov commented on Challenge: Why is this wrong?</title><description>I guess because we don't know how CreateSingleInstance is implemented :)
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment21</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment21</guid><pubDate>Mon, 19 Oct 2009 13:51:01 GMT</pubDate></item><item><title>Luis Abreu commented on Challenge: Why is this wrong?</title><description>I think that code will only run initialization once (for the 1st thread that access the value). The correct approach would be to wrap the field in a property which checks for null before returning a reference to that field.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment20</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment20</guid><pubDate>Mon, 19 Oct 2009 13:41:58 GMT</pubDate></item><item><title>Sergey commented on Challenge: Why is this wrong?</title><description>ThreadStaticAttribute indicates that the value of a static field is unique for _each_ thread.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment19</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment19</guid><pubDate>Mon, 19 Oct 2009 13:09:10 GMT</pubDate></item><item><title>Stijn Guillemyn commented on Challenge: Why is this wrong?</title><description>First off, I think a singleton should always be one single instance, not an instance per thread. If you want a single instance per thread, you shouldn't call it a singleton, but threadInstance of something like that.
  
  
Secondly, this code will cause pain. Certainly if you're not executing on the first thread, as stated above, the only thread were the variable would be initialized.
  
  
Thinking of it, would this thread always be the UI thread? Or is this conclusion a bridge too far? If true, code that depends on your 'singleton' instance would then have UI thread affinity? So a null reference check could be used as a check if you're on the UI thread? :)
  
  
Or am I wrong about this?
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment18</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment18</guid><pubDate>Mon, 19 Oct 2009 09:21:45 GMT</pubDate></item><item><title>Mikael Svenson commented on Challenge: Why is this wrong?</title><description>qbik got it spot on. I made this mistake myself in early .net days. It pays to think and read the manual every now and then :)
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment17</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment17</guid><pubDate>Mon, 19 Oct 2009 06:27:30 GMT</pubDate></item><item><title>Krzysztof Kozmic commented on Challenge: Why is this wrong?</title><description>It'll get initialized only on the 1st thread so you'll get NullReferenceException on subsequent threads.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment16</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment16</guid><pubDate>Mon, 19 Oct 2009 05:59:58 GMT</pubDate></item><item><title>Diego Mijelshon commented on Challenge: Why is this wrong?</title><description>Well, qbik basically nailed it, so there's not a lot to say.
  
I might add that calling "singleton" something that will (should) actually have one instance per thread is a semantic mistake.
  
Rule of thumb is, never make a ThreadStatic readonly and never initialize inline. Instead, use an accessor that checks for null.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment15</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment15</guid><pubDate>Mon, 19 Oct 2009 02:21:27 GMT</pubDate></item><item><title>Dmitriy Nagirnyak commented on Challenge: Why is this wrong?</title><description>If CreateSingleInstance will fail mySingleton will be NULL which I doubt is the expected value of it.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment14</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment14</guid><pubDate>Mon, 19 Oct 2009 02:00:47 GMT</pubDate></item><item><title>Mohamed Meligy commented on Challenge: Why is this wrong?</title><description>You'd use ThreadStatic so that you have only one MySingleton in every thread (by default MySingleton  should be only one instance for all threads, using ThreadStatic you have N MySingleton for N threads).
  
  
The problem is that the assignment to a static field  (to "CreateSingleInstance()" return value) is just the same as if it was written inside a static constructor, and a static constructor is called only once, so, the second thread and beyond will not call it, meaning will NOT assign MySingleton a value, and it will remain to default(MySingleton), null.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment13</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment13</guid><pubDate>Mon, 19 Oct 2009 01:07:43 GMT</pubDate></item><item><title>Nick Berardi commented on Challenge: Why is this wrong?</title><description>I think qbik has nailed it.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment12</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment12</guid><pubDate>Mon, 19 Oct 2009 00:53:10 GMT</pubDate></item><item><title>Philip commented on Challenge: Why is this wrong?</title><description>Bad because
  
  
0) Little known - in a asp.net web call, the actual thread used can actually change during the asp.net event processing.  use context instead.
  
  
1) initialization only on the first thread
  
  
2) any threadpool threads will possibly be reused and hence the "thread-specific singleton" will behave oddly.
  
  
3) It's *magic*!
  
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment11</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment11</guid><pubDate>Mon, 19 Oct 2009 00:42:53 GMT</pubDate></item><item><title>John Simons commented on Challenge: Why is this wrong?</title><description>Because the ThreadPool reuses threads.
  
Specially bad in web scenarios, because the web pipeline uses the ThreadPool to handle requests.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment10</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment10</guid><pubDate>Mon, 19 Oct 2009 00:12:30 GMT</pubDate></item><item><title>alberto commented on Challenge: Why is this wrong?</title><description>Because different threads will have different instances of the field, so it's not a Singleton anymore, AND only one of the threads will be properly initialized with a MySingleton type, the others will be null.
  
  
PD: A free *Rhino Mocks* license? Is it the "Ultimate" version or what? :D
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment9</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment9</guid><pubDate>Sun, 18 Oct 2009 23:29:13 GMT</pubDate></item><item><title>Bill Barry commented on Challenge: Why is this wrong?</title><description>While I dislike the usage of the tread static attribute in general, This case in particular you seem to be suggesting you want a singleton but here you will not have a singleton.
  
  
In place of the thread static attribute, I like to use the following pattern (which I also use for accessing cache and session):
  
  
    public class Memoize {
  
        public static T Execute
&lt;t(string key, Func
&lt;t getter) {
  
            var obj = (T)CallContext.GetData(key);
  
  
            if (!Equals(obj, default(T))) {
  
                return obj;
  
            }
  
  
            obj = getter();
  
            CallContext.SetData(key, obj);
  
            return obj;
  
        }
  
    }
&gt;</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment8</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment8</guid><pubDate>Sun, 18 Oct 2009 23:04:10 GMT</pubDate></item><item><title>Dmitry commented on Challenge: Why is this wrong?</title><description>The initializer will run only once during appdomain initialization, not on every thread.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment7</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment7</guid><pubDate>Sun, 18 Oct 2009 22:09:01 GMT</pubDate></item><item><title>Thilak Nathen commented on Challenge: Why is this wrong?</title><description>Darn!
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment6</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment6</guid><pubDate>Sun, 18 Oct 2009 22:00:54 GMT</pubDate></item><item><title>Frank commented on Challenge: Why is this wrong?</title><description>Initialization of ThreadStatic variables only happen once. So on other threads the value will be the default value, being null for reference types.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment5</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment5</guid><pubDate>Sun, 18 Oct 2009 21:42:32 GMT</pubDate></item><item><title>Ayende Rahien commented on Challenge: Why is this wrong?</title><description>Thilak,
  
That is actually a bug in my post about a bug :-)
  
Fixed, thanks for spotting this.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment4</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment4</guid><pubDate>Sun, 18 Oct 2009 21:40:51 GMT</pubDate></item><item><title>Thilak Nathen commented on Challenge: Why is this wrong?</title><description>... or should I say, no variable type.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment3</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment3</guid><pubDate>Sun, 18 Oct 2009 21:26:28 GMT</pubDate></item><item><title>Thilak Nathen commented on Challenge: Why is this wrong?</title><description>No return type?
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment2</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment2</guid><pubDate>Sun, 18 Oct 2009 21:25:18 GMT</pubDate></item><item><title>qbik commented on Challenge: Why is this wrong?</title><description>hmm, maybe this is the reason:
  
"Note:   Do not specify initial values for fields marked with ThreadStaticAttribute, because such initialization occurs only once, when the class constructor executes, and therefore 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, or to a null reference (Nothing in Visual Basic) if it is a reference type." (MSDN)
  
  
So you would have correct instance for the first thread that access the singleton, and null's for all other threads. And the readonly flag stops you from initializing the field in any other place.
</description><link>http://ayende.com/4253/challenge-why-is-this-wrong#comment1</link><guid>http://ayende.com/4253/challenge-why-is-this-wrong#comment1</guid><pubDate>Sun, 18 Oct 2009 21:10:18 GMT</pubDate></item></channel></rss>