开发者

ASP.NET: the static instance will get volatile?

If I implement a Singleton as follows, putting into App_Code, will the instance be reclaimed by GC after each round-trip HTTP requests? Or it'll still persist in the runtime? Thanks for any help.

public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    static Singleton()
    {
    }

    Singleton()
    {
    }

    public static Singleton Instance
    {
     开发者_运维问答   get
        {
            return instance;
        }
    }
}


No, not on each HTTP request. To prove that, I added a readonly timestamp to the class:

public readonly DateTime Timestamp = DateTime.Now;

and then referenced it on a page in the project. It remained the same on each refresh.

You mention the GC. Remember that there is no guarantee of when the GC will reclaim an object (even GC.Collect() I don't think guarantees an object will be reclaimed). But I don't think that that is the gist of your question.

Basically, yes your singleton will act as a singleton, at least until the application is recycled.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜