Object Oriented Programming Patterns for Geeks

The Thread Context Singleton

[Please see Simple Singleton first]

The CLR of the .NET framework has its quirks, some good, some not so good.  One of the nicer quirks is the ability it has to attach static contexts to individual threads of execution and to do this you simply add the 'ThreadStaticAttribute' to a static member. 

The advantage to these Singletons in .NET is that you don't have to think about thread safety (usually) as they are inaccessible to other threads.  Another advantage is that being available only to the thread they instantiate on is that you can harness the advantages of a Singleton whilst knowing that the data will never be altered elsewhere.  The downside to this of course is that if you need access to the singleton across thread boundaries you will need to consider using a different Singleton type. 

In use this form of singleton has a less complicated implementation.  Being in a position to basically ignore the various locking mechanisms required in Multithreaded Programming you can pretty much just write the class as you would normally.  However, I have stated this form of Singleton as more complicated simply because .NET's memory model breaks away from the norm in this instance.  So far (please prove me wrong somebody) .NET is the only environment this is possible in, so for people familiar to the more traditional Singleton/static combination, this may throw you a little.

sealed class ThreadSingleton
{
    /// <summary>
    /// This holds the actual instance 
    /// (based on Thread Context context)
    /// </summary>
    [ThreadStatic]
    private static ThreadSingleton _Me;

    /// <summary>
    /// Some basic instance data.
    /// </summary>
    private string _SomeInstanceData;

    /// <summary>
    /// Gets or sets some instance data.
    /// </summary>
    /// <value>Some instance data.</value>
    public string SomeInstanceData
    {
        get { return this._SomeInstanceData; }
        set { this._SomeInstanceData = value; }
    }

    /// <summary>
    /// Initializes a new instance of the 
    /// <see cref="ThreadSingleton"/> class.
    /// This is privately invoked
    /// </summary>
    private ThreadSingleton()
    {
        this._SomeInstanceData = "Hi!";
    }

    /// <summary>
    /// Gets the singleton.
    /// </summary>
    /// <value>The singleton.</value>
    public static ThreadSingleton Singleton
    {
        get
        {
            if( _Me == null )
                _Me = new ThreadSingleton();

            return _Me;
        }
    }
}