0

Im trying to invoke a method on a new thread in a winforms c# app. But I need the method name to come from a string.

Is it possible to do something like:

public void newThread(string MethodName)
{
   new Thread(new ThreadStart(MethodName)).Start();
}

I've tried but cant seem to get this to work?

Any advice would be much appreciated.

Developr
  • 447
  • 8
  • 21
  • 3
    First get a `MethodInfo` through reflection then execute it in another thread code to call it. Just see MSDN about `MethodInfo.Invoke` for an example – Adriano Repetti Jun 27 '14 at 15:19
  • 1) What is the method's signature? Is it compatible with the non-generic `Action` delegate? 2) Is it a static method, or an instance method? – Kirill Shlenskiy Jun 27 '14 at 15:22
  • 1
    Assuming signature and visibility are compatible with what you need it's just one line: `ThreadPool.QueueUserWorkItem(_ => GetType().GetMethod(methodName).Invoke(this, null));` – Adriano Repetti Jun 27 '14 at 15:25

2 Answers2

1

One way of doing it can be:

public void NewThread(string MethodName, params object[] parameters)
{
    var mi = this.GetType().GetMethod(MethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
    Task.Factory.StartNew(() => mi.Invoke(this, parameters), TaskCreationOptions.LongRunning);
}

void Print(int i, string s)
{
    Console.WriteLine(i + " " + s);
}

void Dummy()
{
    Console.WriteLine("Dummy Method");
}

NewThread("Print", 1, "test");
NewThread("Dummy");
L.B
  • 114,136
  • 19
  • 178
  • 224
0

I am assuming you want to call method from within class itself.

Type classType = this.GetType();
object obj = Activator.CreateInstance(classType)
object[] parameters = new object[] { _objval };
MethodInfo mi = classType.GetMethod("MyMethod");
ThreadStart threadMain = delegate () { mi.Invoke(this, parameters); };
new System.Threading.Thread(threadMain).Start();

If not replace this with class you need.

Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265