c# – 同时调用相同对象的多个线程.它会引起问题吗?

假设我有以下C#类
class MyClass
{
    private int _i;
    private object _locker = new object();

    public void DoSomething()
    {
        var b = 2;

        // some work that depends on b being 2

        lock(_locker)
        {
            _i = 3;
        }

        // some more work

        b = -1;

        // some more work
    }
}

我用这种方式,

//Usage:

var myobject = new MyClass();
new Thread(new ThreadStart(() => myobject.DoSomething())).Start();
new Thread(new ThreadStart(() => myobject.DoSomething())).Start();

以下序列可以发生吗?

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.

重要的一点是b是局部变量.两个线程是否可以访问b的同一个实例?我理解,对于实例变量_i,会发生这种情况.因此,锁定构造.但我不确定是否需要锁定局部变量.

解决方法

调用者输入DoSomething()方法时,局部变量将被置于堆栈中.每个线程在一个单独的堆栈上运行,并将获得自己唯一的局部变量.

Wikipedia for thread local storage的这一部分也适用于C#线程:

In other words,data in a static or global variable is normally always located at the same memory location,when referred to by threads from the same process. Variables on the stack however are local to threads,because each thread has its own stack,residing in a different memory location.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...