System.Reflection.MethodInfo.Invoke and multiple threads

陌路散爱 提交于 2019-12-01 19:33:09

Since you're wanting to create a new thread with System.Threading.Thread rather than make the call on an existing UI thread or threadpool thread, first thing to notice is that with System.Threading.Thread you can use either a ThreadStart or ParameterizedThreadStart delegate.

You do want parameters to your thread's main method, but ParameterizedThreadStart only allows an object, which forces you to cast it to the required type. So we'll just use a closure to get all the arguments passed across in a type-safe way.

public void InvokeOnNewThread(this MethodInfo mi, object target, params object[] parameters)
{
     ThreadStart threadMain = delegate () { mi.Invoke(target, parameters); };
     new System.Threading.Thread(threadMain).Start();
}

Example usage:

mi.InvokeOnNewThread(obj, parameters);

If you're working with .NET 2.0, then take out the keyword this from the parameter list and call like:

InvokeOnNewThread(mi, obj, parameters);

This will discard any return value, but so did the unthreaded example in your question. If you need the return value leave a comment.

You can start a thread with an anonymous method:

Thread myThread = new Thread(delegate() {
    object obj = Activator.CreateInstance(typeof(MyClassName));

    object[] _objval = new object[3]; 
    object[] parameters = new object[] { _objval };
    MethodInfo mi = classType.GetMethod("MyMethod");
    mi.Invoke(obj, parameters); 
});
myThread.Start();

The code inside the delegate() { ... } is an anonymous method that is executed on the new thread.

Just a suggestion, why not use .Net 4.0 Framework it has an easier threading implementation. Just use Parallel.For, Parallel.ForEach() or Parallel.Invoke(). Some further explanation here -> http://anyrest.wordpress.com/2010/09/09/parallel-programming-easier-than-ever-using-net-framework-4/

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