不应使用实例变量,因为它们会导致mulithreading问题? [英] Should instance variables not be used since they cause mulithreading problems?

查看:131
本文介绍了不应使用实例变量,因为它们会导致mulithreading问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,实例变量不是线程安全的,因为它们存储在堆上。我重构code在ASP.NET单线程应用程序,我想使用实例变量了。

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).

有没有帮助开发者来决定何时使用实例变量以及何时使用局部变量的任何标准。我用Google搜索这一点,我已经看过MSDN上,但我还没有设法找到一个答案,我的具体的问题。

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.

推荐答案

你有没有做过什么让ASP.NET应用程序单线程?否则,它在默认情况下多踩踏。

Have you done anything to make the ASP.NET application single threaded? Otherwise it's multi treaded by default.

实例变量如果线程之间共享的对象仅仅是多线程应用中的问题。正常为ASP.NET应用程序是,每个线程创建其自己的对象的实例,因此该多线程是没有问题的。

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.

如果您需要在线程之间共享数据,在对象封装的数据仍然是最好的办法。通过使用私有的实例变量,并通过方法或属性访问它们,就可以确保从对象​​以外的所有访问是同步的,因为对象中的code拥有其中数据暴露的完全控制。

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.

这篇关于不应使用实例变量,因为它们会导致mulithreading问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆