当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net - Should instance variables not be used since they cause mulithreading problems?

问题描述:

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.

网友答案:

You are in fact referring to static variables. Static variables are not thread-safe (in general, unless you write code to synchronize appropriate access to the variable). Instance variables, in contrast, are thread-safe in asp.net since each request thread will operate on its own copy.

static variables are meant to store data that needs to be shared among all requests. If you don't have such scenario, you shouldn't need to use static variables. And if you do, there are classes that already provide for this, such as the Cache class.

网友答案:

Assuming are talking about web pages and instance variable of web page then you do not have to worry about the multi-threading and thread safety. The asp.net/web server will take care for that. This msdn article discuss the thread safety provide by asp.net.

分享给朋友:
您可能感兴趣的文章:
随机阅读: