From 07623ddc1a1a41db902b5c3461fda80332ea6d44 Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Thu, 8 Apr 2021 19:31:11 +0200 Subject: [PATCH] Fixed an issue with removing event-based coroutines after several event calls Fixes #14 --- Coroutine/CoroutineHandlerInstance.cs | 11 ++++++----- Tests/EventBasedCoroutineTests.cs | 8 +++++--- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/Coroutine/CoroutineHandlerInstance.cs b/Coroutine/CoroutineHandlerInstance.cs index aba2f9b..6a0247c 100644 --- a/Coroutine/CoroutineHandlerInstance.cs +++ b/Coroutine/CoroutineHandlerInstance.cs @@ -12,7 +12,7 @@ namespace Coroutine { private readonly List tickingCoroutines = new List(); private readonly Dictionary> eventCoroutines = new Dictionary>(); - private readonly HashSet eventCoroutinesToRemove = new HashSet(); + private readonly HashSet<(Event, ActiveCoroutine)> eventCoroutinesToRemove = new HashSet<(Event, ActiveCoroutine)>(); private readonly HashSet outstandingEventCoroutines = new HashSet(); private readonly HashSet outstandingTickingCoroutines = new HashSet(); private readonly Stopwatch stopwatch = new Stopwatch(); @@ -101,12 +101,13 @@ namespace Coroutine { if (coroutines != null) { for (var i = 0; i < coroutines.Count; i++) { var c = coroutines[i]; - if (this.eventCoroutinesToRemove.Contains(c)) + var tup = (c.Event, c); + if (this.eventCoroutinesToRemove.Contains(tup)) continue; if (c.OnEvent(evt)) { - this.eventCoroutinesToRemove.Add(c); + this.eventCoroutinesToRemove.Add(tup); } else if (!c.IsWaitingForEvent) { - this.eventCoroutinesToRemove.Add(c); + this.eventCoroutinesToRemove.Add(tup); this.outstandingTickingCoroutines.Add(c); } } @@ -125,7 +126,7 @@ namespace Coroutine { // RemoveWhere is twice as fast as iterating and then clearing if (this.eventCoroutinesToRemove.Count > 0) { this.eventCoroutinesToRemove.RemoveWhere(c => { - this.GetEventCoroutines(c.Event, false).Remove(c); + this.GetEventCoroutines(c.Item1, false).Remove(c.Item2); return true; }); } diff --git a/Tests/EventBasedCoroutineTests.cs b/Tests/EventBasedCoroutineTests.cs index f1fbb91..5730d96 100644 --- a/Tests/EventBasedCoroutineTests.cs +++ b/Tests/EventBasedCoroutineTests.cs @@ -302,9 +302,9 @@ namespace Tests { } [Test] - public void MovingCoroutineTest() - { + public void MovingCoroutineTest() { var evt = new Event(); + IEnumerator MovingCoroutine() { while (true) { yield return new Wait(evt); @@ -312,7 +312,7 @@ namespace Tests { } } - CoroutineHandler.Start(MovingCoroutine(), "MovingCoroutine"); + var moving = CoroutineHandler.Start(MovingCoroutine(), "MovingCoroutine"); CoroutineHandler.RaiseEvent(evt); CoroutineHandler.RaiseEvent(evt); CoroutineHandler.RaiseEvent(evt); @@ -336,6 +336,8 @@ namespace Tests { CoroutineHandler.RaiseEvent(evt); CoroutineHandler.Tick(1d); CoroutineHandler.RaiseEvent(evt); + + moving.Cancel(); } }