Xaqron
Xaqron

Reputation: 30857

ThreadLocal property

If we have a ThreadLocal property (each thread has it's unique property) then which one is correct (we don't want use automatic setter/getter):

A)

private ThreadLocal<MyClass> _someProperty = new ThreadLocal<MyClass>();

public ThreadLocal<MyClass> SomeProperty
{
    get
    {
        return _someProperty.Value;
    }
    set
    {
        _someProperty.Value = value;
    }
}

B)

private ThreadLocal<MyClass> _someProperty = new ThreadLocal<MyClass>();

public MyClass SomeProperty
{
    get
    {
        return _someProperty.Value;
    }
    set
    {
        _someProperty.Value = value;
    }
}

Upvotes: 2

Views: 2495

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062780

I'm assuming you want to encapsulate the ThreadLocal<T>, so that the caller only needs to know about MyClass; in which case, you still need to access .Value explicitly, as that is where the per-thread magic happens:

private readonly ThreadLocal<MyClass> _someProperty = new ThreadLocal<MyClass>();

public MyClass SomeProperty
{
    get { return _someProperty.Value; }
    set { _someProperty.Value = value; }
}

Upvotes: 4

SLaks
SLaks

Reputation: 887453

You should use the second form, to ensure that you control when the value is set.

If you expose the ThreadLocal directly, your caller can write SomeProperty.Value = null, and you won't be able to prevent it.

By forcing all access to go through your class, you can add validation to the setter.

Also, the first form allows one thread to erase the property's values on other threads by replacing the entire ThreadLocal instance.

Note that your code won't compile; you need to return and set .Value.

Upvotes: 2

Related Questions