A large network of objects that have the same object reference

I have a large network of nodes in memory, everyone has a link to the same object.

As an example. Suppose every node on the network has this class.

public class Node { /** This is the shared object **/ public Context context { get; private set; } public Node Parent { get; private set; } public List<Node> Children { get; private set; } public Node(Context pContext, Node pParent, List<Node> pChildren) { this.context = pContext; this.Parent = pParent; this.Children = pChildren; } } 

The context property is an object that is passed to the constructor for all nodes in the network.

Assuming that the network is very large (thousands of nodes), and they form a tree structure. Will this common shared link between them lead to memory leaks?

If I detach a branch in the tree by setting Parent to Null . Will this thread correctly garbage collection in C# , even if context remains a reference to this shared object?

What coding practices should be used to ensure proper operation.

+4
source share
2 answers

Assuming that the network is very large (thousands of nodes), and they form a tree structure. Will this common shared link between them lead to memory leaks?

No, it should not be.

If I detach a branch in the tree by setting Parent to Null. Will this thread be the correct C # garbage collection, even if the context remains a reference to this shared object?

Yes it should. The only time this could potentially be a problem, you subscribe to events of longer-lived objects, since event subscriptions create a link to your class. A simple call to context will not affect your class being built.

The main problem is that objects will collect garbage as soon as nothing can "reach" your object through links. Your objects can still hold links to other objects, it matters only for another.

+6
source

Your node refers to the context, so your node prevents garbage collection. Not the other way around.

Setting Parent to null will not cause the node to be garbage collected. As long as your node refers to some other class, it will remain in memory.
In your specific code, you need to remove the node from its parent children so that it is garbage collected.

+3
source

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


All Articles