我在调用从 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
方法?这样我将为每个调用的方法运行单独的线程。
最佳答案
如果您知道所有动态加载类型都实现了 Run,是否可以只要求它们都实现 IRunable 并去掉反射部分?
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();
}
关于C# : Invoke a method with [Type]. InvokeMember() 在单独的线程中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/505523/