How and when are c# Static members disposed?

一笑奈何 提交于 2019-11-28 08:54:49

The static variable of your class are not garbage collected until the app domain hosting your class is unloaded. The Dispose() method will not be called, because it is an instance method, and you said that you wouldn't create any instances of your class.

If you would like to make use of the Dispose() method, make your object a singleton, create one instance of it, and dispose of it explicitly when your application is about to exit.

public class MyClass : IDisposable {
    public IList List1<int> {get; private set;}
    public IDictionary<string,string> Dict1 {get; private set;}
    public void Dispose() {
        // Do something here
    }
    public static MyClass Instance {get; private set;}
    static MyClass() {
        Instance = new MyClass();
    }
    public static void DisposeInstance() {
        if (instance != null) {
            Instance.Dispose();
            Instance = null;
        }
    }
}
Guido Kleijer
public class Logger : IDisposable
{

    private string _logDirectory = null;
    private static Logger _instance = null;

    private Logger() : this(ConfigurationManager.AppSettings["LogDirectory"])
    {
        AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
    }

    private Logger(string logDirectory) 
    {
    } 

    public static Logger Instance
    {
        get
        {
            if (_instance == null)
                _instance = new Logger();
            return _instance;
        }
    }

    private void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Dispose();
    }



    public void Dispose()
    {
        // Dispose unmanaged resources
    }
}

You should dispose this objects manually, there is no way to create a "finalizer" for static resources.

If you really want to have static members which keep references to unmanaged objects just create a method for disposing the unmanaged objects and "force" consumer to use it on exit.

By "force" I mean document your class with a paragraph that states "when" and "why" to use this "dispose" method. Do it either if you are the sole consumer (or your code...) or you plan to distribute your class. Also try to use a somehow descriptive name (to that "dispose" method) such as "DisposeStatics", "AlwaysDispose", "DisposeAtEnd" etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!