带有 Web 应用程序的单例模式,不是一个好主意! [英] Singleton pattern with Web application, Not a good idea!

查看:36
本文介绍了带有 Web 应用程序的单例模式,不是一个好主意!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些有趣的东西,我在调试其他东西时幸运地注意到了它.我正在应用 MVP 模式,并制作了一个单例控制器以在所有演示文稿之间共享.

I found something funny, I notice it by luck while I was debugging other thing. I was applying MVP pattern and I made a singleton controller to be shared among all presentations.

突然我发现某些事件在第一次回发时调用一次,如果有两次回发则调用两次,如果有 100 次回发则调用 100 次.

Suddenly I figured out that some event is called once at first postback, twice if there is two postback, 100 times if there is 100 postbacks.

因为 Singleton 基于保存实例的静态变量,并且该静态变量存在于回发中,所以我连接事件假设它将连接一次,并为每次回发重新连接.

because Singleton is based on a static variable which hold the instance, and the static variable live across postbacks, and I wired the event assuming that it will be wired once, and rewired for each postback.

我认为在 Web 应用程序中应用单例之前我们应该三思而后行,否则我会错过什么??

I think we should think twice before applying a singleton in a web application, or I miss something??

谢谢

推荐答案

由于共享状态,在多线程应用程序(不仅仅是单例模式)中使用静态对象时,您应该三思而后行.应该应用适当的锁定机制以同步对共享状态的访问.如果不这样做,可能会出现一些非常难以发现的错误.

You should think twice any time you are using static objects in a multi-threaded application (not only the singleton pattern) because of the shared state. Proper locking mechanisms should be applied in order to synchronize the access to the shared state. Failing to do so some very difficult to find bugs could appear.

这篇关于带有 Web 应用程序的单例模式,不是一个好主意!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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