开发者

If you attach an event to a form handler, and don't remove it, can the form and object be garbage collected when form closed?

Here is scenario.

FormA loads. ClassA is instantiated at the form class scope. User does something that causes event ClassA.SomeEvent to be handled by method FormA.SomeEventHandler() User closes FormA

Now what happens when the garbage collector makes its rounds?

Since FormA should be disposed, but a reference to it is made by ClassA.

ClassA is still referenced in the FormA scope.

So how is this handled?

  1. The way .NET handles form 开发者_运维百科closing, it removes all references to objects in its scope, which removes the reference to ClassA allowing ClassA to be collected, and then FormA no longer is referenced by ClassA so it can be collected?

  2. .NET refuse to collect FormA because it's referenced by ClassA, and thus does not collect ClassA as well?

  3. .NET collect FormA but refuse to collect ClassA because it has a handler attached to it's event (even though it no longer points to an existing object)?

My understanding is that either 1 or 2 is correct, and I am leaning towards 2, but don't doubt 1 or 3 are possible.


If ClassA has a reference to FormA (through the event handler) and FormA has a reference to ClassA (through holding it as a field), but nothing else has a reference to either of these objects, the GC will detect the circular reference and collect them both.

The key to whether an object will be garbage collected is if any "roots" hold a reference to the object. Roots include local variables in the currently-executing method(s) and static properties on classes. If the GC can't find a path from a root to an object, it will be garbage collected. In your example, if there are no references from any other objects to ClassA and FormA, the GC can't find a path from a root to those objects, and will collect them both.

For more information, I recommend Garbage Collector Basics and Performance Hints.


What you’ve described is essentially the problem with reference counting. I think .NET uses a mark-and-sweep algorithm for GC, which means that as long as nothing else references ClassA and FormA, they will be considered garbage and will be destroyed (assuming I’m not missing something subtle with regards to events and forms).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜