I just came across the question – is the access of an object safely possible across threads in C#.
E.g. with the code
//Somewhere long ago MyClass myVar = new MyClass('First Instance'); //Then later, happening at the same time //In thread one myVar = new MyClass('Second Instance'); //In thread two myVar.PrintName();
I don’t care whether the first or the second instance is used, but is it possible that myVar is at some point not valid at all (e.g. pointing to a non existing location, because maybe the object reference is only partly updated before used in the other thread)
Side question about locks:
If I leave a lock – are then all outstanding writes committed to memory?
My question here is if I reference a variable in a lock, I know only one thread can access the lock at the same time – but can it happen that I write to the variable in one thread (and the write is only done to the cache), and after that in the other thread even inside the lock getting the old value of the variable (because the cache is not committed or I still have an old value in the cache of this thread)?
To your first. Its almost certainly safe but I would lock it none the less.
As to your cache question what cache are you talking about, the only ones I can think of are the CPU caches, if we had worry about whether these we’re dirty and needed flushing we’d all be in a lot of trouble.
Edit: From your comment I see that the CPU cache is what you are refering to.
Mutli-core and Multi-processor hardware ensures that any data in a cache that is out-of-date will not be used.