Reputation: 35395
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
}
Upvotes: 0
Views: 1998
Reputation: 9986
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.
}
}
}
Upvotes: 1
Reputation: 158399
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
.
Upvotes: 5