如何以及何时是C#静态成员的处置? [英] How and when are c# Static members disposed?

查看:100
本文介绍了如何以及何时是C#静态成员的处置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类具有广泛的静态成员,其中一些保存引用托管和非托管对象。

I have a class with extensive static members, some of which keep references to managed and unmanaged objects.

有关实例,静态构造只要类型引用调用,这会导致我类旋转任务的一个的BlockingQueue。发生这种情况时的静态方法之一是所谓的,例如

For instance, the static constructor is called as soon as the Type is referenced, which causes my class to spin up a blockingQueue of Tasks. This happens when one of the static methods is called, for example.

我实现了IDisposable,这给我的方法来处理的处理上我创建的任何实例对象。然而,这些方法都不会被调用,如果消费者没有从我的类中创建的任何实例对象。

I implemented IDisposable, which gives me methods to handle disposal on any instance objects I created. However, these methods are never called if the consumer doesn't create any instance objects from my class.

如何及在哪里我把code处置我的类的静态部分保持引用?我一直认为,当最后一个实例对象被释放处置静态引用的资源发生;这是我第一次有史以来在可能永远不会创建任何实例的类。

How and where do I put code to dispose of references maintained by the static portion of my class? I always thought that disposal of static-referenced resources happened when the last instance object was released; this is the first time I've ever created a class where no instances may ever be created.

推荐答案

类的静态变量不是垃圾收集,直到应用程序域托管类被卸载。该的Dispose()方法将不会被调用,因为它是一个实例方法,你说,你会不会创建任何类实例。

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.

如果你想利用的Dispose()的方法,让你的对象单身,创建它的一个实例,并处理它明确当你的应用程序即将退出。

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;
        }
    }
}

这篇关于如何以及何时是C#静态成员的处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆