C#:使用[Type].InvokeMember()在单独的线程中调用方法

7

我正在使用这段代码,其中我调用了从dll动态加载的类列表的run方法:

for (int i = 0; i < robotList.Count; i++)
{
    Type t = robotList[i]; //robotList is a List<Type>
    object o = Activator.CreateInstance(t);
    t.InvokeMember("run", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, null);
}
invokeMember 调用列表中每个类的 run 方法。
现在我该如何通过 invokeMember 在单独的线程中调用这个 run 方法?这样我就可以为每个调用的方法运行单独的线程。
2个回答

19

如果你知道所有动态加载的类型都实现了Run方法,那么你是否可以要求它们都实现IRunnable接口,并且摆脱反射部分呢?

Type t = robotList[i];
IRunable o = Activator.CreateInstance(t) as IRunable;
if (o != null)
{
    o.Run(); //do this in another thread of course, see below
}

如果不行,可以尝试以下方法:
for (int i = 0; i < robotList.Count; i++)
{
    Type t = robotList[i];
    object o = Activator.CreateInstance(t);
    Thread thread = new Thread(delegate()
    {
        t.InvokeMember("Run", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, null);
    });
    thread.Start();
}

非常好,正是我想要的。感谢提到IRunable...我现在正在尝试它。再次感谢。 - Andreas Grech
太好了...我已经按照你的建议将类改为使用IRunnable接口。 - Andreas Grech

2
看看这个示例,它是一种实现方式:
using System;
using System.Threading;
using System.Reflection;
using System.Collections.Generic;

namespace Obfuscation
{
    public class Program
    {
        static Type[] robotArray = new Type[] { typeof(Program) };
        static List<Type> robotList = new List<Type>(robotArray);

        internal void Run()
        {
            Console.WriteLine("Do stuff here");
        }

        internal static void RunInstance(object threadParam)
        {
            Type t = (Type)threadParam;
            object o = Activator.CreateInstance((Type)t);
            t.InvokeMember("Run", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, o, null);
        }

        public static void Main(string[] args)
        {
            for (int i = 0; i < robotList.Count; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(RunInstance), robotList[i]);
            }
        }
    }
}

该死,我发表之前还刷新了页面 :) - OJ.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接