开发者

c#: controlling access to object from different threads

How do I control when a thread is permitted to access an object and when it is not.

For example, if I have situation like below, I want to make sure that when I am doing something with objFoo in my ButtonClick event, I should not be able to touch objFoo from my doSomethingWithObjFoo method.

private void button1_Click(object sender, EventArgs e) {
    // doing som开发者_如何转开发ething 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
}


The easiest way is perhaps to use 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
    }
}

There are other options as well, such as using a ReaderWriterLockSlim.


That what we use lock for.

Thread Synchronization is a must read.

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

    public void Process()
    {

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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜