Invoke method in new thread (method name from string)?

谁都会走 提交于 2019-12-25 01:47:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!