C# : Invoke a method with [Type]. InvokeMember() 在单独的线程中

标签 c# .net multithreading reflection

我在调用从 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/

相关文章:

c# - LINQ to SQL DataContext.Translate 和名称与源名称不同的属性

c# - 创建 ATM 算法

java - ExecutorService 与 AtomicInteger 和 Synchronized 给出不同的结果

c++ - pthread 在一定时间后终止

Java:通过同步实现公共(public)实例变量线程安全

c# - "SignalR"无法识别集线器

c# - Cocoa(Xamarin.Mac)应用程序是否支持System.Drawing.Graphics

.net - .NET 资源文件字符串是否被保留?

.net - 如何在不安装的情况下运行使用 Microsoft Moles 编写的单元测试?

c# - Azure辅助角色抛出System.IO.FileNotFoundException