gpt4 book ai didi

c# - Asp.NET MVC 应用程序中的静态类

转载 作者:太空狗 更新时间:2023-10-29 20:59:31 25 4
gpt4 key购买 nike

我想知道 ASP.NET MVC 应用程序中的静态类是否可以多次初始化。我最初设计我的应用程序是为了让静态组件从数据库中获取一些东西并用作缓存,然后我向从构造函数调用的类添加了一个刷新方法。刷新方法也可通过应用程序的管理部分使用。在某些时候,我注意到数据已更新而无需此手动触发器,这意味着静态构造函数运行了不止一次。

有几种情况我可以合理地看到这种情况发生,例如未处理的 Exception 导致重新初始化。但我无法重现这一点,所以我想确定一下。

最佳答案

最常见的场景是:

  • 重新加载 Web 应用程序

    • 接触了Web.config
    • 触摸二进制文件
    • 异常终止(内存不足、权限错误)
  • 重新加载应用程序池

  • 重启 IIS
  • 重新启动 w3wp.exe(至少每 29 小时一次!)

应用程序域将重新加载(根据需要重新编译动态部分),这将使所有静态初始化的数据无效。

如果创建静态数据的成本很高,您可以通过在某处持久保存静态数据来解决这个问题,或者避免重新加载 AppDomain、应用程序池或 IIS 服务器。

Update: Phil Haack just published a relevant blog entry here: http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx

  • Bye Bye App Domain
    • it does a better job at explaining the above. Notable, IIS will recycle it's worker process very 29 hours at minimum and shared hosters will recycle AppDomain much more often (perhaps in 20 minutes of idle time)
  • So tell ASP.NET, “Hey, I’m working here!”
    • outlines techniques you can apply to get notified of an AppDomain take down - you could use this to get your Singleton instance behaving 'correctly'
  • Recommendation

我建议你阅读它:)

关于c# - Asp.NET MVC 应用程序中的静态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7786823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com