0

In my C# app (.NET 6) One of my class' constructors hooks up to a PropertyChanged notification of one of the arguments passed in. I did it like this:

public ProfileSource(ISystemService sys, Routine routine, Aspect aspect)
    : base(sys)
{
    Routine = routine;
    Aspect = aspect;

    PropertyChangedEventManager.AddHandler(
        Routine,
        (_, _) =>
        {
            RaisePropertyChanged(nameof(Profiles));
        },
        nameof(IRoutine.AreResultsValid));
}

In Debug mode I was was surprised to find my lambda was not being called when the Routine object raises that property changed for its AreResultsValid property.

But when I changed that lambda to instead be a member function of the class, suddenly it started working.

public ProfileSource(ISystemService sys, Routine routine, Aspect aspect)
    : base(sys)
{
    Routine = routine;
    Aspect = aspect;

    PropertyChangedEventManager.AddHandler(
        Routine,
        OnResultsValidChanged,
        nameof(IRoutine.AreResultsValid));
}

private void OnResultsValidChanged(object? sender, PropertyChangedEventArgs args)
{
    RaisePropertyChanged(nameof(Profiles));
}

With this change (and no other), my handler is called every time.

I can switch back and forth and observe the effect. Lambda version: handler not called. Function version: handler called

Can someone tell me why this would be? What am I missing here?

(Edited to add: I use the lambda approach in several other places and it's always worked. Now I'm starting to worry that i need to go and change those all to be functions, just in case)

Joe
  • 5,394
  • 3
  • 23
  • 54
  • 2
    https://stackoverflow.com/a/62621885/17034 – Hans Passant Jun 25 '22 at 23:29
  • Hans, thanks (yet again) for answering me. Would this issue also raise its head with a private, local function? Because I just realized I encountered exactly the same problem when was using local functions for this purpose a while back. I even asked a question about it. I had completely forgotten but it must have a vague memory of that which made me try the member function.. https://stackoverflow.com/questions/71668976/why-does-a-local-function-not-work-with-propertychangedeventmanager – Joe Jun 25 '22 at 23:37
  • 2
    The member function forces `this` to be captured. I can't see what kind of object it refers to. If it is eligible to be garbage collected then the handler stops being called. – Hans Passant Jun 26 '22 at 00:17

0 Answers0