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.
        }
    }
}
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论