c#:控制从不同线程访问对象

时间:2010-09-30 06:22:26

标签: c# .net multithreading thread-safety

如何控制允许线程访问对象的时间以及何时不访问该对象。

例如,如果我遇到类似下面的情况,我想确保当我在ButtonClick事件中使用 objFoo 做某事时,我不应该能够从 doSomethingWithObjFoo 方法中触及 objFoo

private void button1_Click(object sender, EventArgs e) {
    // doing something with objFoo
}

private void timer1_Tick(object sender, EventArgs e) {
    Thread T = new Thread(new ThreadStart(doSomethingWithObjFoo));
    T.Start();
}

private void doSomethingWithObjFoo(){
    // doing something else with objFoo
}

2 个答案:

答案 0 :(得分:5)

最简单的方法是使用lock

private object _fooLock = new object();
private void button1_Click(object sender, EventArgs e) {
    lock(_fooLock)
    {
        // doing something with objFoo
    }
}

private void timer1_Tick(object sender, EventArgs e) {
    Thread T = new Thread(new ThreadStart(doSomethingWithObjFoo));
    T.Start();
}

private void doSomethingWithObjFoo(){
    lock(_fooLock)
    {
       // doing something else with objFoo
    }
}

还有其他选项,例如使用ReaderWriterLockSlim

答案 1 :(得分:1)

我们使用lock作为。

Thread Synchronization是必读的。

public class TestThreading
{
    private System.Object lockThis = new System.Object();

    public void Process()
    {

        lock (lockThis)
        {
            // Access thread-sensitive resources.
        }
    }

}