public void Then(PostAnimationAction action) { lock (this.lockObject) { // Animation already ended. Perform action immediately. if (this.Ended) { new Thread(() => action()).Start(); } else { // Perform action when animation ends. this.AnimationEnded += (_, __) => new Thread(() => action()).Start(); } } }
/// <summary> /// Performs the specified action after all animations finish. /// </summary> /// /// <param name="action"> /// the action to perform after the animation finishes. /// </param> /// /// <remarks> /// This is an alternative to the Await method. The difference /// between this method and Await is that this method will not /// block the current thread, and will instead perform the /// specified action asynchronously when the animations finish. /// /// If no animations are running when this method is called, /// the action will be started immediately, though still /// asynchronously. /// </remarks> public void Then(PostAnimationAction action) { // Keep track of the running animations. this.readerWriterLock.AcquireReaderLock(Timeout.Infinite); var animations = new List <IAnimation>(this.Animations); this.readerWriterLock.ReleaseReaderLock(); // Have each animation remove itself from the list and // alert the new thread when it finishes. foreach (var animation in this.Animations) { animation.AnimationEnded += (a, __) => { lock (this) { animations.Remove(a); Monitor.PulseAll(this); } } } ; // Start a new thread that will wait until the animations are // completed and then perform the action. new Thread(() => { lock (this) { while (animations.Count > 0) { Monitor.Wait(this); } } action(); }).Start(); } }