Will a parent object that is no longer referenced be reclaimed through GC if the parent object itself holds a live reference?

44 views Asked by At

Will a parent object that is no longer referenced be ineligible for collection if it holds a reference to an object that is still alive, like a singleton service that is referenced in other viewmodels?

I've yet to find this explicit situation explained in regards to GC. My inclination is that everythings fine as-is, because ParentViewModel doesn't "own" the service, it will still be reclaimed.

Consider these scenarios..

public class MainClass
{
    public SingletonService SingletonService{ get; }

    public void DoSomething()
    {
        using (ParentViewModel parentVM as new ParentViewModel(this.SingletonService))
        {
            // Work.
        }
    }
}

public class ParentViewModel : INotifyPropertyChanged, IDiposable
{
    private readonly SingletonService _service;

    public ParentViewModel(SingletonService singleton)
    {
        this._service = _service;
    }
    
    public void Dispose(bool disposing)
    {
        // Will my readonly reference to a living singleton prevent the ParentViewModel from being reclaimed?
    }
}

Will my readonly reference to a living singleton prevent the ParentViewModel from being reclaimed?

public class ParentViewModel : INotifyPropertyChanged, IDiposable
{

    public SingletonService SingletonService{ get; }
    
    public void Dispose(bool disposing)
    {
        // Do I need to null the SingletonServiceproperty to allow for ParentViewModel to be reclaimed?
        // What if SingletonService has bindings to a view?
    }

    public bool SomeValue
    {
        get => this.SingletonService.OtherValue
    }

}

Do I need to null the SingletonService property to allow for ParentViewModel to be reclaimed?

What if SingletonService has bindings to a view?

Would I need to also set SomeValue to null because it uses the service to bind through?

1

There are 1 answers

0
TP95 On

GC will reclaim all memory that is inaccessible.

Since the references are uni-directionaly, the singleton (and basically any other objects for that matter) have no idea about the existence of ParentViewModel so that will be freed by the GC without having any impact on the program.