Does holding a reference to an object will keep it in memory if the reference will never be used?

安稳与你 提交于 2019-12-11 04:56:12

问题


I have a collection with WeakReferences to object. The object are loaded dynamically during runtime, and can be collected by GC randomly.

Occasionally, I need to permanently delete an object, this is done with asynchronous DB command. Meaning - there is a time period between the delete command and the actual commiting of the deletion in the persistency database where the object can be GCed, and then reloaded from the DB.

The easiest way for me to solve this would be to have a 'Deleted' flag in each object (already have one), and when performing the deletion action, add a strong reference to the deleted object to the DB Command object, so when the operation completes the strong reference is lost and the object can be released forever.

The question is, is the GC allowed to collect my object with read-ahead? does it apply in this scenario? Am i guaranteed the that object will not be collected until the DB command is dequeued and processed?

Here is some lower level details:

Dictionary<Int64, WeakReference> mItems;
struct IOCommand
{
    public CommandDetails command;
    public object[] strongReferences;
}
Queue<IOCommand> mIOQueue;
void queueCommand(CommandDetails command, object relatedObject)
{...}

You can see that when queuing a command I pass a related object as a strong reference kept in the queue until it is processed, but as the object are not used the question is can they be optimized away...

Amit.


回答1:


As long as your code has a (non-weak) reference to an object it will not be collected.

So you should be safe, the very fact that a (future) Db Command will use the reference makes sure it will still be be there.

Just make sure you don't rely on a WeakReference in this case, that strong reference should have an appropriate lifespan.


but as the object are not used the question is can they be optimized away...

No. The way you store them will make sure they exist as long as the command is stored in the Queue, and as long as the queue is reachable of course.

But note that if they are really not used it shouldn't even matter...




回答2:


The GC should never remove anything with a reference to it. WeakReference is the exception where you've specifically opted into letting it collect the stuff you're referencing. If the DB Command has a reference to the object to be deleted, you'll be fine.



来源:https://stackoverflow.com/questions/10471817/does-holding-a-reference-to-an-object-will-keep-it-in-memory-if-the-reference-wi

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