global.asax范围和生命周期澄清 [英] global.asax scope and lifetime clarification

查看:80
本文介绍了global.asax范围和生命周期澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在当前正在研究的项目中实现几个应用程序级的行为. 我需要做好几件事: 1.我在哪里以及如何定义应用程序级变量? 2.这些变量的寿命是多少?或更准确地说,在什么情况下将其丢弃? (应用程序池回收?应用程序二进制文件从内存中删除并在下一个请求时重新编译?等等.) 3. global.asax文件是放置会话计数器的好地方,还是将值存储到DB/文件是持久保存此类数据的更好方法?

I need to implement several application-level behavior in a project I'm currently working on. There are several things I need to get my head around: 1. Where and how do I define application level variables? 2. What is the lifetime of these variables? or more accuratly, in what scenarios are they discarded? (Application pool recycle? App binaries dropped from memory and recompiled on the next request? etc.) 3. Is the global.asax file a good place to put a session counter, or maybe storing the value to a DB / file is a better way of persisting this kind of data?

欢迎任何评论或想法. 谢谢! -Elad

Any comments or ideas are welcome. Thank you! -Elad

推荐答案

应用程序级变量具有应用程序生存期.这意味着应用程序池被回收,将被丢弃.
可以出于多种原因回收应用程序池.可以对IIS 6/7进行配置,以便在一定时间后,一定数量的请求之后或以指定的时间间隔回收应用程序池. 您可以通过以下方式设置应用程序变量:

Application-level variables have an application life-time. It means that it the application pool is recycled, they're discarded.
The application pool can be recycled for different reasons. IIS 6/7 can be configures so that the app pool is recycled after a certain amount of time, after a certain number of request or at specified intervals. You set an application variable this way:

Application["DbConfig"] = "my value";

,但是如果您尝试在其他位置进行设置/访问,则必须意识到可能会遇到的问题.您必须采用一种在更新变量时将其锁定的方法.

but you have to be aware of the problems you might encounter if you try to set/access in different place. You have to adopt a way to lock the variables when they're updated.

我为所有配置参数提供web.config,然后创建了自己的类,用于存储应用程序字段:

I us the web.config for all the configuration parameters and then I've created my own class which I use to store application fields:

namespace Web.My
{
    public class Application
    {
        public static string ApplicationStorageFolder
        {
            get
            {
                return (System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~"), "_AppStorage"));
            }
        }
    }
}

如果需要设置一些字段,则在应用程序启动时执行Application_Start 如果您需要保留信息,则可以创建自己的配置文件(xml或简单文本)以在应用程序启动和关闭时存储和读取值.您可以将类序列化为XML文件,这样就可以准备就绪,轻松地重新填充属性. 一个分贝也可以. 我会对会话计数器执行相同的操作.

If I need set some fields I do it at the application startup Application_Start If you need to persist infos you can create your own config file (xml or simple text) to store and read values at the application startup and shutdown. You can serialize your class in a XML file so you can ready it, repopulating your properties easily. A db would be fine as well. I would do the same with the session counter.

这篇关于global.asax范围和生命周期澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆