3

Please, consider this simple function:

public void BeginFade() 
{
    var fade = new DoubleAnimation(0d, TimeSpan.FromSeconds(1));
    fade.Completed += Fade_Completed;
    grid.BeginAnimation(OpacityProperty, fade);
}

The scope of var fade is the function BeginFade and as far as I understand when the DoubleAnimation class has completed its task, the Framework will clear the resources automatically.

Is this correct?

And what about the event handler? When I call more times BeginFade() what happens to the event Completed?

This example is just to better understand the underlying behaviors. Of course I might declare fade as a class member and set the event Completed in the constructor...

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Mark
  • 4,338
  • 7
  • 58
  • 120
  • has completed its task, the Framework will clear the resources automatically---perhaps not, the clr will also check its references – Lei Yang Mar 14 '17 at 08:03
  • 1
    It depends if your grid keeps a reference to fade. If it does it can't be cleared. – Carra Mar 14 '17 at 08:05
  • 2
    http://stackoverflow.com/questions/4526829/why-and-how-to-avoid-event-handler-memory-leaks – Selman Genç Mar 14 '17 at 08:07
  • 2
    You passed your `fade` to `BeginAnimation` so in general you now have no idea when it will be garbage collected, because `BeginAnimation` (in theory) might store it in static field or otherwise keep reference to it. As for completed event - and what can happen to it? `fade` is new every time you call `BeginFade` and so is it's `Completed` event. – Evk Mar 14 '17 at 08:13

1 Answers1

2

So your fade was passed to BeginAnimation, which means that you can not know when it will be disposed of. But I think that in this case, your guess is correct.

With each call to BeginFade you create new fade object and then Fade_Completed event handler subscribes to its Completed event. So every one of your fade animations has exactly one Fade_Completed subscription. That will not stop fade objects from being garbage collected if that is what you are asking.

Max
  • 310
  • 3
  • 7
  • Yes, that is what I was asking. But like other comments suggest, it should be better to declare `fade` as class member, to have more control of what happens. – Mark Mar 14 '17 at 08:35
  • @Mark there is no reason to declare it as class member, what you are doing now is fine (I assume that is WPF animation). – Evk Mar 14 '17 at 09:02
  • Yes, it is! Thanks again. – Mark Mar 14 '17 at 09:06