Do event handlers stop garbage collection from occurring?

后端 未结 4 1520
离开以前
离开以前 2020-11-22 06:01

If I have the following code:

MyClass pClass = new MyClass();
pClass.MyEvent += MyFunction;
pClass = null;

Will pClass be garbage collected

4条回答
  •  醉梦人生
    2020-11-22 06:32

    The moment a piece of memory is no longer referenced it becomes a candidate for garbage collection. When the instance of your class goes out of scope, it is no longer referenced by your program. It is no longer used and therefore can be safely collected.

    If you are not sure wether something will get collected ask yourself the following question: does there still exist a reference to it? The event handlers are referenced by the object instance, not the other way around.

提交回复
热议问题