Skip to content

Enqueue action with parameter of type T. #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 44 additions & 6 deletions UnityMainThreadDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,26 @@ public void Enqueue(IEnumerator action) {
}
}

/// <summary>
/// Locks the queue and adds the Action to the queue
/// <summary>
/// Locks the queue and adds the Action to the queue
/// </summary>
/// <param name="action">function that will be executed from the main thread.</param>
public void Enqueue(Action action)
{
Enqueue(ActionWrapper(action));
}

/// <summary>

/// <summary>
/// Locks the queue and adds the Action (with a parameter T) to the queue
/// </summary>
/// <param name="action">function (requires parameter of type T) that will be executed from the main thread.</param>
/// <param name="arg">parameter of type T to pass to action.</param>
public void Enqueue<T>(Action<T> action, T arg)
{
Enqueue(ActionWrapper(action, arg));
}

/// <summary>
/// Locks the queue and adds the Action to the queue, returning a Task which is completed when the action completes
/// </summary>
/// <param name="action">function that will be executed from the main thread.</param>
Expand All @@ -82,14 +92,42 @@ void WrappedAction() {
return tcs.Task;
}

/// <summary>
/// Locks the queue and adds the Action to the queue, returning a Task which is completed when the action completes
/// </summary>
/// <param name="action">function that will be executed from the main thread.</param>
/// <returns>A Task that can be awaited until the action completes</returns>
public Task EnqueueAsync<T>(Action<T> action, T arg)
{
var tcs = new TaskCompletionSource<bool>();

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<T>(Action<T> action, T arg)
{
action(arg);
yield return null;
}

private static UnityMainThreadDispatcher _instance = null;

public static bool Exists() {
Expand Down