Example code:
MyObject myObject = new MyObject ();
public void FunA () // accessed from thread 1 (when user click a button)
{
myObject = null;
// do some stuff
myObject = new MyObject ( someNewValues );
}
public void FunB () // accessed from thread 2 (calling using timer or smth.)
{
int x = myObject.ReadX ();
}
In most cases it works OK, but when FunA will make myObject null and in same time FunB will access it, application will crash.
Question: How to do that, when thread 1 will access FunA, thread 2 cannot enter FunB?
Update: I tried locks before, but the problem is FunB is calling event to thread 1 (GUI) (guiForm.Invoke) and thread 1 will stuck before FunA { lock… }.
You can lock
myObjectso that only the current thread can use it.This will prevent
FunBfrom accessingmyObjectuntil it has been released by the lock.Update
As pointed out in the comments, it’s probably not a good idea to modify the object that you have a lock on. In this case you can simply have an object that you lock and an object that you modify such that: