System.Reflection.MethodInfo.Invoke和多个线程

编程入门 行业动态 更新时间:2024-10-26 16:32:09
本文介绍了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和多个线程

本文发布于:2023-11-12 13:43:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581660.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   线程   Reflection   System   Invoke

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!