问题
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.
回答1:
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.
回答2:
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");
来源:https://stackoverflow.com/questions/24455306/invoke-method-in-new-thread-method-name-from-string