System.Reflection.MethodInfo.Invoke和多个线程 [英] System.Reflection.MethodInfo.Invoke and multiple threads

查看:65
本文介绍了System.Reflection.MethodInfo.Invoke和多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何使用带有线程的参数调用System.Reflection.MethodInfo.Invoke().

Hi how do i call System.Reflection.MethodInfo.Invoke() with paramters with threads.

例如.

说我有一个方法,可以让您传递代表一个字符串的字符串.类名并动态调用相应的类方法,现在我想用线程调用此Methodinfo.invoke,我不知道如何执行此操作,因为我正在调用带有参数的invoke.代码片段被赋予了优先权.谢谢您的帮助

Say I have a method that allows you to pass in a string that represents a class name and calls corresponding class method dynamically , now i want to call this Methodinfo.invoke with threads ,I have no idea how to do this since i am calling invoke with paramter . Code snippet given meblow . Thank you for your help

Type classType = objAssembly.GetType("MyClassName");
object obj = Activator.CreateInstance(classType)
bject[] _objval = new object[3]; 
object[] parameters = new object[] { _objval };
MethodInfo mi = classType.GetMethod("MyMethod");
mi.Invoke(obj, parameters);  // <---**How do i call this with threads.. ????**

推荐答案

由于您要使用 System.Threading.Thread 创建一个新线程,而不是在现有的UI线程上进行调用还是线程池线程,首先要注意的是,通过 System.Threading.Thread ,您可以使用 ThreadStart ParameterizedThreadStart 委托.

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.

您确实想要线程主方法的参数,但是 ParameterizedThreadStart 仅允许 object ,这迫使您将其强制转换为所需的类型.因此,我们将仅使用闭包以类型安全的方式获取传递的所有参数.

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();
}

示例用法:

mi.InvokeOnNewThread(obj, parameters);

如果您使用的是.NET 2.0,则从参数列表中删除关键字 this 并按以下方式调用:

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.

这篇关于System.Reflection.MethodInfo.Invoke和多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆