Reputation: 1355
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.
Upvotes: 1
Views: 283
Reputation: 273854
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...
Upvotes: 3
Reputation: 13205
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.
Upvotes: 1