ASP.NET 中的单例
如果我在 asp.net 中的集合周围有一个单例包装器,它是否必须被缓存,或者它的数据是否会在回发期间保留?
此外,如果另一个用户登录该应用程序,该应用程序是否会创建另一个实例(自身),从而创建该单例的另一个实例,或者它是否会访问在第一个实例中创建的相同单例?
单例的实际实现是以下之一: (设计 1:)
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
或设计 2:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
If i have a singleton wrapper around a collection in asp.net does it have to be cached or would it's data be persisted across post backs?
Also if another user logs into the app would the app create another instance (of itself) and therefore another instance of the singleton or would it access the same singleton that was created in the first instance?
The actual implementation of the singleton is one of the following:
(Design 1:)
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
or Design 2:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要应用程序正在运行,静态变量就会存在,直到应用程序重新启动。它将存在于回发和用户之间。
本文介绍如何实现静态单例: http://msdn.microsoft.com /en-us/library/ff650316.aspx
对于您正在尝试做的事情是否还有其他会影响单例实现的要求?
A static variable will exist as long as the application is running, until a application restart. It would exist across postbacks and users.
This article shows how to implement a static singleton: http://msdn.microsoft.com/en-us/library/ff650316.aspx
Are there any more requirements on what you are trying to do that would affect the implementation of the singleton?
Singleton 是一种确保所有请求只有一个实例的模式。由于您已将其声明为静态,因此它在应用程序的生命周期内存在。并且相同的实例将返回给通过您的属性请求该对象的任何用户。
Singleton is pattern that makes sure there is only one instance for all request. Since you have declared it static it exists for lifetime of the application. And the same instance will be returned to any user requesting the object through your property.