-1

In the following code

public class ClassA
{
    [ThreadStatic]
    private static ClassB _b;
    protected static B
    {
        get { return _b; }
        set { _b = value; }
    }

    ...

    public void SomeMethod(Data data)
    {
        ...
        B.SomeVoidMethod(data);
        ...

        B = null;
    }
}

public class ClassB
{
    private ClassB() {}

    private ClassC _c;
    public C
    {
        get { return _c; }
    }

    public static ClassB MyMethod(Data data)
    {
        ClassB b = new ClassB();
        b._c = C.GetObject(data);

        return b 
    }
}

i get NullReferenceException in SomeMethod. I suppose that other thread calls this method and makes B null, but (if I understand ThreadStatic) other threads should not be allowed to access B.

I can't just use:

get
{
    if (_b == null)
        _b = new B();
}

because changing B constructor to public and using it this way will give me an instance of B with some properties (e.g. C) being null.

I also tried to set lock inside SomeMethod - didn't solve the problem.

I'd like to avoid modifications in classB. Is it possible to prevent exceptions without it?

  • You have not guaranteed that operator new is called on each thread prior to accessing _b, so you have essentially asked for this misbehavior. The normal way to do ThreadStatic is to wrap it in a static property that news up the backing field if it's null. – hoodaticus Mar 03 '17 at 16:33
  • 1
    Use (ThreadLocal)[https://msdn.microsoft.com/en-us/library/dd642243(v=vs.110).aspx] instead. – Alessandro D'Andria Mar 03 '17 at 16:38
  • Thanks @AlessandroD'Andria . I did it, but ThreadLocal is new to me and I'm not sure how to use ThreadLocal valueFactory function in this case as I need to use ClassB.MyMethod(Data data) instead of constructor. Could you please briefly explain? – Grzegorz Pawłowski Mar 03 '17 at 18:11

1 Answers1

1

ThreadStatic means each thread has its own version of the field. You are getting NullReferenceExceptions because you did not initialize the field on the thread that is accessing it.

From the very top of the doc: "Indicates that the value of a static field is unique for each thread."

https://msdn.microsoft.com/en-us/library/system.threadstaticattribute(v=vs.110).aspx

hoodaticus
  • 3,772
  • 1
  • 18
  • 28