Skip to content

Commit aea7ba8

Browse files
authored
Merge pull request PimDeWitte#11 from DamianMehers/master
Add an async variant of Enqueue
2 parents c7958b5 + c775cdb commit aea7ba8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

UnityMainThreadDispatcher.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,32 @@ public void Enqueue(Action action)
5656
{
5757
Enqueue(ActionWrapper(action));
5858
}
59+
60+
/// <summary>
61+
/// Locks the queue and adds the Action to the queue, returning a Task which is completed when the action completes
62+
/// </summary>
63+
/// <param name="action">function that will be executed from the main thread.</param>
64+
/// <returns>A Task that can be awaited until the action completes</returns>
65+
public Task EnqueueAsync(Action action)
66+
{
67+
var tcs = new TaskCompletionSource<bool>();
68+
69+
void WrappedAction() {
70+
try
71+
{
72+
action();
73+
tcs.TrySetResult(true);
74+
} catch (Exception ex)
75+
{
76+
tcs.TrySetException(ex);
77+
}
78+
}
79+
80+
Enqueue(ActionWrapper(WrappedAction));
81+
return tcs.Task;
82+
}
83+
84+
5985
IEnumerator ActionWrapper(Action a)
6086
{
6187
a();

0 commit comments

Comments
 (0)