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?