How and when to recycle / garbage collect a singleton instance

I am using a Singleton instance created from a nested class. This instance contains several static collections that are cleared when Singleton is deleted, but the problem is that I get a link to a non-zero remote singleton that is not properly garbage collected.

I would like to know WHEN AND HOW to completely dispose and garbage collect my Singleton instance, so when the instance is requested again after dispose (and set to null), a new instance is created.

I use the following nested template for a Singleton instance:

public class SingletonClass : IDisposable { private List<string> _collection; private SingletonClass() { } public static SingletonClass Instance { get { return Nested.Instance; //line 1 - this line returns the non-null instance after dispose and setting the Singleton instance to null which is causing problems } } private void Init() { _collection = new List<string>(); //Add data to above collection } public void Dispose() { //Release collection _collection.Clear(); _collection = null; } class Nested { static Nested() { Instance = new SingletonClass(); Instance.Init(); } internal static readonly SingletonClass Instance; } } 

The problem in line 1 is that after removing SingletonClass from the client class, the _collection object becomes null, while the SingletonClass instance remains non-empty even after setting = null.

+4
source share
1 answer

You will need to implement System.IDisposable if you fulfill the following basic requirements:

The main use of this interface is the release of unmanaged resources.

Then I would go to the class destructor and call Dispose() as an example .

Otherwise

The garbage collector automatically frees the memory allocated to the managed object when this object is no longer in use.

(which will not happen with a real singleton, unless the process is complete)

You might be better off if you use sth like this

 class PseudoSingleton<T> where T : new() { private readonly object _lock = new object(); private T _instance; public T Instance { get { lock (this._lock) { if (this._instance != null) { this._instance = new T(); } return this._instance; } } } public void Reset() { lock (this._lock) { this._instance = null; } } } 
+4
source

Source: https://habr.com/ru/post/1391219/


All Articles