views:

50

answers:

2

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 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
}
+5  A: 

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.

Fredrik Mörk
I would not try to lock the object on the UI Thread (i.e. in the button1_Click handler) unless you are sure that you will not have to wait very long. Your UI will freeze until the button1_Click handler finishes.
Ray Henry
+1  A: 

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.
        }
    }

}
KMan