Skip to content

Commit af611be

Browse files
committed
Improve async task handling in AwaitCoroutine
Use an callback-based approach to stop the AwaitCoroutine once the associated Task is completed, instead of polling every frame. This makes the AwaitCoroutine class more efficient.
1 parent 73bc304 commit af611be

File tree

1 file changed

+8
-30
lines changed

1 file changed

+8
-30
lines changed

src/Coroutines/AwaitCoroutine.cs

Lines changed: 8 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,12 @@ public AwaitCoroutine(Task<T> task)
1818
this.Task = task;
1919
}
2020

21-
private void TryEnd()
22-
{
23-
if (Task.IsCompleted)
24-
{
25-
Kill();
26-
}
27-
}
28-
2921
public override void OnEnter()
3022
{
31-
TryEnd();
32-
if (isAlive) ResumeUpdates();
33-
}
34-
35-
public override void Update()
36-
{
37-
TryEnd();
23+
// As the CoroutineManager class is not thread safe, ensure that Kill()
24+
// is executed on the main Godot thread.
25+
var godotTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
26+
Task.ContinueWith(result => Kill(), godotTaskScheduler);
3827
}
3928
}
4029

@@ -52,23 +41,12 @@ public AwaitCoroutine(Task task)
5241
this.Task = task;
5342
}
5443

55-
private void TryEnd()
56-
{
57-
if (Task.IsCompleted)
58-
{
59-
Kill();
60-
}
61-
}
62-
6344
public override void OnEnter()
6445
{
65-
base.OnEnter();
66-
TryEnd();
67-
}
68-
69-
public override void Update()
70-
{
71-
TryEnd();
46+
// As the CoroutineManager class is not thread safe, ensure that Kill()
47+
// is executed on the main Godot thread.
48+
var godotTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
49+
Task.ContinueWith(result => Kill(), godotTaskScheduler);
7250
}
7351
}
7452
}

0 commit comments

Comments
 (0)