开发者

C# .NET Singleton life of app pool

I want to create a singleton that remains alive for the life of the app pool using HttpContent.Current.Cache.

Where would I create 开发者_如何学Gothe class and how should it be implemented? I understand how to implement a singleton but am not too familiar with threading and httpcontent.current.cache.

Thanks!


It doesn't matter where to put the singleton code.

As soon as you access the instance and the type is initialized, it will remain in memory for the entire life of your ApplicationDomain. So use it as a normal class and the rest is done on first use.


Perhaps you are over-complicating the issue? i'm not sure why you need to use the cache. Could you not just add a file to the App_Code folder to house your class e.g "mSingleton.cs"

public sealed class mSingleton
{
    static readonly mSingleton _instance = new mSingleton();

    public int MyVal { get; set; }

    public static mSingleton Instance
    {
        get { return _instance; }
    }
    private mSingleton()
    {
        // Initialize members, etc. here.
    }
}

Then it is global to all your code and pages, maintains state until the app pool recycles or there is a app rebuild (i don't know if this causes the app to recycle as well - if it does then it suits your criteria anyway), doesn't need to be added to any cache, application or session variables.. no messy handling

You can do this on page_load in any aspx.cs file and refresh it to see the count go up each time to prove state is maintained:

mSingleton getMyObj = mSingleton.Instance;
getMyObj.MyVal++;


I'd not use the cache for this. I'd recommend a static class or singleton with static getInstance().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜