- Изменено
TrackEntry lifetime
Hi,
I would like to know what is the best way to work with delegate, as I am not confident how the TrackEntry life cycle works under the hood.
I want a one-time event when this specific animation ends and never again.
Two options, which is better?
var trackEntry = skeletonAnimation.SetAnimation(0, someAnimation, false);
trackEntry.End += _ => DoSomethingOnEnd();
// Fire and forget about unsubscribing
Or
var trackEntry = skeletonAnimation.SetAnimation(0, someAnimation, false);
trackEntry.End += OnEnd;
//...
private void OnEnd(TrackEntry trackEntry)
{
trackEntry.End -= OnEnd; // Doing unsubscription - is this step necessery??
DoSomethingOnEnd();
}
I am using almost all the time the second pattern just to be careful, but is it really needed? The first one is obviously simpler.
There is no need to use the longer second idiom in case of the End
delegate. It is guaranteed to be called at most once (see the documentation here). If you are curious about the implementation details, the TrackEntry is "freed" (put back into a pool) after the End
event (and the subsequent Dispose
event immediately following it) has been issued.