加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 静态字段初始化程序有时在Application_start之前运行

发布时间:2020-12-16 07:09:01 所属栏目:asp.Net 来源:网络整理
导读:我有一个ASP.NET Web应用程序,它开始显示一些非常奇怪的行为.这是一些示例代码: // in Bar.cspublic class Bar { public static Baz baz = Something.Step2();}// in Global.asaxpublic void Application_Start(...) { Something.Step1();} 故事的简短版本
我有一个ASP.NET Web应用程序,它开始显示一些非常奇怪的行为.这是一些示例代码:

// in Bar.cs
public class Bar {
    public static Baz baz = Something.Step2();
}

// in Global.asax
public void Application_Start(...) {
    Something.Step1();
}

故事的简短版本是这样的:在某些机器上,Something.Step2在Something.Step1之前执行并且抛出一个不可处理的异常.在其他计算机上,Step1在Step2之前正确执行. Global.asax及其使用的所有对象根本不涉及Bar.

什么时候静态字段应该相对于其他编程元素执行?为什么两台机器(Win7 64位,包括.NET 4.0,相同的IIS版本等)以不同的顺序执行操作?订单在每台机器上也是一致的.在我的机器上,它总是在Step1之前执行Step2,但是在我的同事的机器上它总是在Step2之前执行Step1.

非常感谢帮助.

更新我找到了访问我的静态字段的根本原因.我的示例中的“Bar”类实际上是一个自定义身份验证模块,并在web.config中作为System.webServer下的Authentication处理程序引用.如果我从web.config中删除该行,我的系统首先调用Step1,从不调用Step2.我的问题巧妙地改为:“为什么web.config导致我的静态初始化器被触发,为什么它会在Application_Start执行之前触发它们?”

解决方法

当您没有静态构造函数时,静态字段初始值设定项在第一次访问之前的“依赖于实现”时间初始化.这意味着它们可以随时初始化 – 您不能依赖Bar.Baz的初始化在第一次使用Bar时发生.

向Bar添加静态构造函数会将此行为更改为您所期望的更多行为.

有关详细信息,请阅读C#语言规范10.5.5.1节:

10.5.5.1 Static field initialization

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class,execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise,the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

另请参见10.2,有关静态构造函数的详细信息:

The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

· An instance of the class type is created.

· Any of the static members of the class type are referenced.

话虽这么说,如果需要确定性初始化,我强烈建议在Something中添加静态构造函数,并在那里正确进行初始化.除了在这种情况下提供初始化顺序的保证之外,它还将阻止另一个类使用Something导致您的代码在将来中断.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读