Invalidating an object reference while another thread is executing a method on it (.NET)
-
18-09-2019 - |
Question
(I'm interested in the .NET CLR)
What exactly happens when one thread changes the object a variable references while another thread is executing a method on the original object?
For example, say the type Foo
has a variable 'Bar' of the type Bar
, and Bar
has no class-level state (for now at least, I'd like to keep this scenario simple):
// Thread 1
foo.Bar = new Bar();
foo.Bar.SomeMethod();
In the meantime, before this finishes executing ...
// Thread 2
foo.Bar = new Bar();
What happens to the method that is (was?) executing on Thread 1? Is everything it needs to complete already on the stack?
Does it change things if thread 2 does this instead?
foo.Bar = null;
Solution
If the call is guaranteed to already be inside SomeMethod()
, then nothing unusual will happen - this
is an implicit argument for methods, so it would never use the value of the field (or property, whichever it is) directly.
Whether you can truly guarantee that is another matter.
OTHER TIPS
-- edit: corrected confusing sentence.
Well, actually assigning to the variable will be atomic, so it's not like the call will suddenly realise 'oh my I'm null!' while executing .SomeMethod()
What can happen, though, is that foo.Bar.SomeMethod() itself will not be called, because Thread 2 will have (maybe) set it to null first; so it just won't execute (it will crash with a null ref exception).
Same applies with your first example; it'll just call .SomeMethod on the new object.
I think you're thinking things may change while .SomeMethod is running, right? No. Nothing will change in there. It will still have the context of itself.
What exactly happens when one thread changes the object a variable references while another thread is executing a method on the original object?
What happens is that you rewrite your code to properly synchronize access to these fields.