pookie pookie - 3 months ago 23
C# Question

Pass parameter to action dispatcher

I have a class which dispatches

Actions
from a queue. However, my
InvokeLater
only takes in an
Action
, without any parameters.

Here is my
Dispatcher
:

public class Dispatcher : MonoBehaviour
{
private static readonly Queue<Action> tasks = new Queue<Action>();
public static Dispatcher Instance = null;

static Dispatcher()
{
Instance = new Dispatcher();
}

private Dispatcher(){ }

public void InvokeLater(Action task)
{
lock (tasks)
{
tasks.Enqueue(task);
}
}

void FixedUpdate()
{
while (tasks.Count > 0)
{
Action task = null;

lock (tasks)
{
if (tasks.Count > 0)
{
task = tasks.Dequeue();
}
}

task();
}
}
}


I use it like this:

var action = new Action(RequestPrediction);
Dispatcher.Instance.InvokeLater(action);


Where
RequestPrediction
is a parameterless function -- which I would like to change so that it (
RequestPrediction
) takes an
int
argument.

How can I change my
Dispatcher
so that I can do something like:

var action = new Action(RequestPrediction);
Dispatcher.Instance.InvokeLater(action,5);


?

Answer

Simplest solution:

var action = new Action(() => RequestPrediction(5));
Dispatcher.Instance.InvokeLater(action);

Otherwise, you'd have to develop your framework and you'd end up with something which tries to look like the existing TPL library in .NET or existing Dispatcher implementation. Which are other, even better suggestions.

Comments