I don’t like switch statement. However, I cannot produce any alternative idea to situation as follow. Give me an idea please.
// Parses MyTask object and routes for execution at a new task
private void PerformTask(MyTask task)
{
Action<object> taskAction = null;
// routing
switch (task.Command)
{
case "MethodX":
taskAction = MethodX;
break;
case "MethodY":
taskAction = MethodY;
break;
default:
break;
}
if (taskAction == null)
return;
Task t1 = Task.Factory.StartNew(taskAction, task);
}
private void MethodX(MyTask task)
{
// do it something
}
private void MethodY(MyTask task)
{
// do it something different
}
// task holder struct
public struct MyTask
{
public string Command;
public int[] Args;
public int Id;
public MyTask(string command, int[] args, int id)
{
this.Command = command;
this.Args = args;
this.Id = id;
}
}
// Gets next task as a MyTask object and performs it.
// Thread method that is polls task queue
private void DoSomeWorks()
{
...
MyTask task = GetNextTask();
PerformTask(task);
...
}
I have some different tasks that should run asynchronously. These are held as MyTask struct.
In DoSomeWorks method, the next task is taken from my task queue and then passed to PerformTask method for execution. PerformTask method (nitty-gritty) determines that which method will be processed for the task. I just implemented this routing operation with switch case statement. But, I want to do this dynamically. How can I invoke the methods dynamically with command string?
I tried something like this;
MethodInfo methodInfo = typeof(MyClass).GetMethod(task.Command);
but I cannot convert from MethodInfo to Action. Well, I need help.
EDIT :
Thanks for your answers. I have tried both suggestions. This is what i need:
private void PerformTask(MyTask task)
{
MethodInfo methodInfo = typeof(MyClass).GetMethod(task.Command);
if (methodInfo != null)
Task.Factory.StartNew(() => methodInfo.Invoke(this, new object[] { task }));
}
I don’t need Action object anymore. So, I can pass generic param object to Methods. Thank you so much
What about: