0

When assigning the Task property with a value, and binding the value with a delegate eventhandler. Does the value get selected for the GarbageCollection once a new value passes by? As per my understanding because the system does no longer have a reference to the old value, it gets flagged for garbage collection.

  private ITask _task;

  public ITask Task
        {
            get => _task;
            private set
            {
                if(_task != value)
                {
                    if(value != null)
                        value.PropertyChanged += (s, e) =>
                            {
                                if(((ITask)s).Status == TaskStatus.Ready)
                                    RaisePropertyChanged(nameof(ButtonCommand));
                            };

                    _task = value;
                    RaisePropertyChanged();
                }
            }
        }


M.B.
  • 997
  • 3
  • 11
  • 25
  • 1
    You are not unsubscribing `value` from the event handler, and as such it will never be collected, meaning your event handler will be called multiple times. You need to unsubscribe `_task` before with `-=`, this means you'll also either need a reference to your anonymous function like [so](https://stackoverflow.com/questions/183367/unsubscribe-anonymous-method-in-c-sharp) or make a method out of your handler – MindSwipe May 27 '20 at 11:57

1 Answers1

1

As per this answer, the anonymous event handler will not prevent garbage collection. However, any object that read Task before the new value is assigned and still holds the result will keep a reference to the old value of Task, preventing garbage collection.

Wibble
  • 796
  • 1
  • 8
  • 23