Disposable singleton in C#

前端 未结 8 1840
Happy的楠姐
Happy的楠姐 2020-12-05 08:14

I have a singleton that uses the \"static readonly T Instance = new T();\" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for u

8条回答
  •  没有蜡笔的小新
    2020-12-05 08:51

    You could use a nested lazy singleton (See here) with some simple modifications:

    public sealed class Singleton : IDisposable
    {
        Singleton()
        {
        }
    
        public static Singleton Instance
        {
            get
            {
                if (!Nested.released)
                    return Nested.instance;
                else
                    throw new ObjectDisposedException();
            }
        }
    
        public void Dispose()
        {
             disposed = true;
             // Do release stuff here
        }
    
        private bool disposed = false;
    
        class Nested
        {
            // Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit
            static Nested()
            {
            }
    
            internal static readonly Singleton instance = new Singleton();
        }
    }
    

    Remember to throw ObjectDisposedException in all public methods/properties of the object if it has been disposed.

    You should also, provide a finalizer method for the object, in case Dispose doesn't get called. See how to correctly implement IDisposable here.

提交回复
热议问题