C# ASP.NET 静态变量的生命周期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8919095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lifetime of ASP.NET Static Variable
提问by paul simmons
I am holding some information in static variables defined in page class (not in Global.asax). I only declare variable in code like:
我在页面类中定义的静态变量中保存了一些信息(而不是在 Global.asax 中)。我只在代码中声明变量,如:
protected static int SomeGlobalUnsecureID;
protected static string SomeGlobalUnsecureString;
and define the variable in PageLoad event. For example, I check ID from the database, if it's different from SomeGlobalUnsecureID, I update SomeGlobalUnsecureID and String from somewhere else, otherwise leave them as is. This is perfectly safe in my app. logic (i.e. those data are not secure, everybody can access them, no problem); only thing I want to accomplish is
并在 PageLoad 事件中定义变量。例如,我从数据库中检查 ID,如果它与 SomeGlobalUnsecureID 不同,我从其他地方更新 SomeGlobalUnsecureID 和 String,否则保持原样。这在我的应用程序中是完全安全的。逻辑(即那些数据不安全,每个人都可以访问它们,没问题);我唯一想要完成的是
Hold the same amount of memory regardless of users connected
Change if and only if persistent info is different from the one in 'memory' (because actually reading the string is time consuming for me.
无论用户连接多少,都保持相同的内存量
当且仅当持久信息与“内存”中的信息不同时才更改(因为实际上读取字符串对我来说很耗时。
Now, since I make the check in PageLoad, I have no problems in reloaded pages. However my page is full of WebMethods, and sometimes I see that the static variables are zeroed. And the strange part is; the session is still active even when the static variables are zeroed (so-> no server or app. pool restart etc.)
现在,由于我在 PageLoad 中进行了检查,因此重新加载的页面没有问题。然而,我的页面充满了 WebMethods,有时我看到静态变量被归零。奇怪的是; 即使静态变量归零,会话仍然处于活动状态(因此-> 没有服务器或应用程序。池重新启动等)
This is really strange for me. I assume that static variable will hold its value until the application (somehow) ends. But even the Session did not expire, the static variable is zeroed. What do you suggest? Is using application variables a better choice? All documents I've read on web suggest static variables instead of application variables, do I need to declare them somehow different?
这对我来说真的很奇怪。我假设静态变量将保持其值,直到应用程序(以某种方式)结束。但即使 Session 没有过期,静态变量也被清零。你有什么建议?使用应用程序变量是更好的选择吗?我在网上阅读的所有文档都建议使用静态变量而不是应用程序变量,我是否需要以某种方式声明它们?
采纳答案by Aristos
Static variables persist for the life of the app domain. So the two things that will cause your static variables to 'reset' is an app domain restart or the use of a new class. In your case with static variables stored in an aspx Page class, you may be losing the static variables when ASP.NET decides to recompile the aspx Page into a new class, replacing the old page class with the new one.
静态变量在应用程序域的生命周期内持续存在。因此,将导致您的静态变量“重置”的两件事是应用程序域重新启动或使用新类。在您的情况下,静态变量存储在 aspx 页面类中,当 ASP.NET 决定将 aspx 页面重新编译为新类,用新页面类替换旧页面类时,您可能会丢失静态变量。
For those reasons if the system decide to restart or replace the class (.NET doesn't kill or unload classes/assemblies in a running app domain) then your static variables will reset because you are getting a new class with the restart or replacement. This applies to both aspx Pages and classes in the App_Code folder
出于这些原因,如果系统决定重新启动或替换类(.NET 不会终止或卸载正在运行的应用程序域中的类/程序集),那么您的静态变量将重置,因为您将通过重新启动或替换获得一个新类。这适用于 App_Code 文件夹中的aspx 页面和类
ASP.NET will replace a class if for any reason thinks that need to recompile it (see ASP.NET dynamic compilation).
如果出于某种原因认为需要重新编译一个类,ASP.NET 将替换它(请参阅 ASP.NET 动态编译)。
You can't prevent the loss of static variables from an app domain restart, but you can try to avoid it from class replacement. You could put your static variables in a class that is not an aspx page and is not in the App_Code directory. You might want to place them on a static classsomewhere in your program.
您无法防止因应用程序域重新启动而丢失静态变量,但您可以尝试通过类替换来避免它。您可以将静态变量放在一个不是 aspx 页面且不在 App_Code 目录中的类中。您可能希望将它们放在static class程序中的某个位置。
public static class GlobalVariables
{
public static int SomeGlobalUnsecureID;
public static string SomeGlobalUnsecureString;
}
The static variables are per pool, that is means that if you have 2 pools that runs your asp.net site, you have 2 different static variables. (Web garden mode)
静态变量是每个池的,这意味着如果您有 2 个池运行您的 asp.net 站点,则您有 2 个不同的静态变量。(网络花园模式)
The static variables are lost if the system restarts your asp.net application with one of this way.
如果系统使用其中一种方式重新启动您的 asp.net 应用程序,则静态变量将丢失。
- the pool decide that need to make a recompile.
- You open the app_offline.htm file
- You make manual restart of the pool
- The pool is reach some limits that you have define and make restart.
- For any reason you restart the iis, or the pool.
- 池决定需要重新编译。
- 你打开 app_offline.htm 文件
- 您手动重新启动池
- 池已达到您定义的某些限制并重新启动。
- 无论出于何种原因,您都需要重新启动 iis 或池。
This static variables are not thread safe, and you need to use the lockkeyword especial if you access them from different threads.
这个静态变量不是线程安全的,如果你从不同的线程访问它们,你需要使用lock关键字。
Since an app restart will reset your statics no matter what, if you really want to persist your data, you should store the data in a database using custom classes. You can store information per-user in Session Statewith a database session state mode. ASP.NET Application State/Variables will not help you because they are stored in memory, not the database, so they are lost on app domain restart too.
由于无论如何重启应用程序都会重置您的静态数据,如果您真的想保留数据,您应该使用自定义类将数据存储在数据库中。您可以存储每个用户的信息会话状态与数据库会话状态模式。ASP.NET 应用程序状态/变量不会帮助您,因为它们存储在内存中,而不是数据库中,因此它们也会在应用程序域重启时丢失。
回答by Aristos
Static variable is used to store the all the object for same value
静态变量用于存储相同值的所有对象
protected void Page_Load(object sender, EventArgs e)
{
sss s1, s2;
s1 = new sss();
s1.TotalMark = 10;
s2 = new sss();
s2.TotalMark = 20;
sss.SchoolName = "St.Joseph's Hr.Sec.S"; //We can access through class and assign common to all
s1.PrintData();
s2.PrintData();
}
public class sss
{
public static string SchoolName { set; get; }
public int TotalMark { set; get; }
public string StudentName{set;get;}
public void PrintData()
{
Console.WriteLine(TotalMark);
Console.WriteLine(SchoolName);
Console.WriteLine(StudentName);
}
}
回答by sotn
I think the following two points are also important for the lifetime of static variables:
我认为以下两点对于静态变量的生命周期也很重要:
1 - In your application pool's advanced settings check "Recycling" -> "Regular Time Interval (minutes)" setting. It's default value is 1740 which means in each 29 hours your static variables are lost because of recycling of your application pool. This setting is used for termination of possible memory leaks. I would not change this setting..
1 - 在您的应用程序池的高级设置中,选中“回收”->“固定时间间隔(分钟)”设置。它的默认值是 1740,这意味着每 29 小时你的静态变量都会因为应用程序池的回收而丢失。此设置用于终止可能的内存泄漏。我不会改变这个设置..
2 - In your application pool's advanced settings check "Process Model" -> "Idle Time-out (minutes)" setting. It's default value is 20 which means in each 20 minutes of inactivity in your application pool, the worker processes are terminated/suspended which will cause your static variables to be lost. This setting is used for freeing up resources when the application pool is not used in some amount of time. You can set it to 0 to disable the timeout.
2 - 在您的应用程序池的高级设置中,选中“进程模型”->“空闲超时(分钟)”设置。它的默认值是 20,这意味着在您的应用程序池中每 20 分钟不活动,工作进程就会终止/暂停,这将导致您的静态变量丢失。此设置用于在一段时间内未使用应用程序池时释放资源。您可以将其设置为 0 以禁用超时。

![C# 如何将 Byte[] 转换为 BitmapImage](/res/img/loading.gif)