HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Is this a thread safe way to control access to a reusable resource? Is there a better way?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thiscontrolresourcewaybetterreusablethreadsafethereaccess

Problem

public static class ThreadStatic where T : new()
{
    [ThreadStatic]
    private static T instance;

    public static T Instance
    {
        get { return instance ?? (instance = new T()); }
    }
}


Used like this:

var probability = ThreadStatic.Instance.NextDouble();


  • Can this be broken? (Like, am I missing a volatile somewhere?)



  • Is there an existing pattern for this? Is there a better way to do this?



  • What would be an elegant way to allow for constructor parameters to be specified?



  • Would this be better suited to an IOC container?

Solution

-
I'm not sure to be honest, the contained resource would be specific per thread and created upon first read so volatile may be unnecessary as I believe that's for multiple threads reading and writing to the same field.

-
It looks like you are trying to make a singleton version of the ThreadLocal class, unless you have a good reason I would suggest that you just use that instead.

-
The ThreadLocal class allows for a factory method (as a Func) to be supplied to create a more complex object.

-
It depends on the type of resource you want to use in this manner, if it is a service or resource then yes an IOC may be a better option as most containers allow an instance per thread. However if you just need per thread storage of a field, then ThreadLocal is a better option. It also allows the resource to be properly disposed if required too.

Context

StackExchange Code Review Q#18059, answer score: 4

Revisions (0)

No revisions yet.