Access through "Instance" to the class "Toggle ()" threadsafe? If so, under what assumptions, rules, etc. If not, why and how can I fix this?
No, it is not thread safe.
In principle, both threads can run the Toggle function at the same time, so this can happen.
// thread 1 is running this code if(value == 0) { value = 1; // RIGHT NOW, thread 2 steps in. // It sees value as 1, so runs the other branch, and changes it to 0 // This causes your method to return 0 even though you actually want 1 } else if(value == 1) { value = 0; } return value;
You need to work with the following assumption.
If 2 threads work, they can alternate and interact with each other randomly at any point. You can halfway write or read a 64-bit integer or float (on a 32-bit processor), and another thread can jump in and modify it from under you.
If 2 threads never have access to anything at all, it doesn’t matter, but once they do, you should stop them from stepping on each other. The way to do this in .NET is with locks.
You can decide what and where to block by thinking about such things:
For a given block of code, if the value of something has changed from under me, will it matter? If that were the case, you need to block this something for the duration of the code, where it matters.
Looking at your example again
// we read value here if(value == 0) { value = 1; } else if(value == 1) { value = 0; } // and we return it here return value;
To return this value, suppose that value will not change between reading and return . For this assumption to be truly correct, you need to lock value throughout this entire code block.
So you would do this:
lock( value ) { if(value == 0) ...
HOWEVER
In .NET, you can only block link types. Int32 is a value type, so we cannot block it.
We will solve this by introducing the 'dummy' object and blocking it wherever we want to block the "value".
This is what Ben Sheyrman is talking about .