And*_*ech 7 .net c# reflection multithreading
我正在使用此代码,我正在调用run从dll动态加载的类的List方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
在invokeMember被调用run推法每一类在列表中.
现在我如何在一个单独的线程中调用此run方法invokeMember?这样我就可以为每个被调用的方法运行单独的线程.
Rex*_*x M 19
如果您知道所有动态加载的类型都实现了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
}
Run Code Online (Sandbox Code Playgroud)
如果没有,这将有效:
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();
}
Run Code Online (Sandbox Code Playgroud)