.NET中静态变量的生命周期

fea*_*net 10 .net c# static

我有一个使用一些配置设置的扩展方法.我已经宣布这些为static.

public static class Extensions
{
    static string _mailServer = ConfigurationManager.AppSettings["MailServer"];
    // ... etc    

    public static void SendEmailConfirmation(this IOrder order) { }
}
Run Code Online (Sandbox Code Playgroud)

我只是想检查一下这是否符合我的意图,因为我并不是100%肯定.我的想法是,我不想继续阅读这些值,我希望它们能够被读取一次,并在Web应用程序的生命周期中进行缓存.这会发生什么?谢谢

Mic*_*ren 16

(根据KeithS的说明更新,直到首次使用时才读取)

They will be read the first time they are used, and then retained until the AppDomain is stopped or recycled, which is probably what you want.

That is, ASP.NET apps run inside an AppDomain. This is how they are resident and available to multiple requests without having to startup for each individual request. You can configure how long they live and when they recycle, etc. Static variables live and die with the app and thus will survive as long as the app is resident in the app domain.

  • 是的,直到十几个人进来澄清所有不是100%真实的边缘情况......;) (3认同)
  • 基本上这个.更具体地说,静电学在首次需要时会被懒惰地评估.这样可以节省预先初始化一堆静态的启动成本.因此,第一次运行SendEmailConfirmation()时,它将访问应用程序设置,并将在应用程序域的生命周期内持续存在(将运行直到应用程序池或IIS重置;第一次会自动不时发生,另一种是通过用户选择或在服务器重启时发生的) (3认同)