diff --git a/UnityMainThreadDispatcher.cs b/UnityMainThreadDispatcher.cs index 7a4f783..6bb6565 100644 --- a/UnityMainThreadDispatcher.cs +++ b/UnityMainThreadDispatcher.cs @@ -49,16 +49,26 @@ public void Enqueue(IEnumerator action) { } } - /// - /// Locks the queue and adds the Action to the queue + /// + /// Locks the queue and adds the Action to the queue /// /// function that will be executed from the main thread. public void Enqueue(Action action) { Enqueue(ActionWrapper(action)); } - - /// + + /// + /// Locks the queue and adds the Action (with a parameter T) to the queue + /// + /// function (requires parameter of type T) that will be executed from the main thread. + /// parameter of type T to pass to action. + public void Enqueue(Action action, T arg) + { + Enqueue(ActionWrapper(action, arg)); + } + + /// /// Locks the queue and adds the Action to the queue, returning a Task which is completed when the action completes /// /// function that will be executed from the main thread. @@ -82,14 +92,42 @@ void WrappedAction() { return tcs.Task; } + /// + /// Locks the queue and adds the Action to the queue, returning a Task which is completed when the action completes + /// + /// function that will be executed from the main thread. + /// A Task that can be awaited until the action completes + public Task EnqueueAsync(Action action, T arg) + { + var tcs = new TaskCompletionSource(); + + void WrappedAction() { + try + { + action(arg); + tcs.TrySetResult(true); + } catch (Exception ex) + { + tcs.TrySetException(ex); + } + } + + Enqueue(ActionWrapper(WrappedAction)); + return tcs.Task; + } IEnumerator ActionWrapper(Action a) { a(); yield return null; } - - + + IEnumerator ActionWrapper(Action action, T arg) + { + action(arg); + yield return null; + } + private static UnityMainThreadDispatcher _instance = null; public static bool Exists() {