I understand that instance variables are not thread safe because they are stored on the heap. I am refactoring code in an ASP.NET single threaded application and I am trying to use instance variables more.
My question is: do developers avoid using instance variables because of possible multi threading problems? (even if the app is not multi threaded now it may be in the future). I remember reading that instance variables should be used to improve design using composition and aggregation rather than association (as with local variables).
Is there any criteria that helps a developer to decide when to use instance variables and when to use local variables. I have Googled this and I have looked on MSDN but I have not managed to find an answer to my specific question.
Have you done anything to make the ASP.NET application single threaded? Otherwise it’s multi treaded by default.
Instance variables is only a problem with multi threaded applications if you share the object between threads. Normal for an ASP.NET application is that each thread creates its own instances of the objects, so the multi threading is not a problem.
If you need to share data between threads, encapsulating the data in an object is still the best approach. By using private instance variables and access them through methods or properties, you can make sure that all access from outside the object is synchronised, as the code in the object has full control over where the data is exposed.