Suppose I have the following C # class
class MyClass { private int _i; private object _locker = new object(); public void DoSomething() { var b = 2;
And I use it that way
//Usage: var myobject = new MyClass(); new Thread(new ThreadStart(() => myobject.DoSomething())).Start(); new Thread(new ThreadStart(() => myobject.DoSomething())).Start();
Can the following sequence happen?
Thread 1 is halfway through its work. Thread 2 just starts. Sets b = 2. Thread 1 sets b = -1. Thread 2 is confused because it expected b to be 2 but its -1.
The important point is that b is a local variable. Will two threads access the same instance of b? I understand that for the _i instance variable this will happen. Therefore, the lock construct is built for this. But I'm not sure if I need to block local variables.
source share