C#:在一个单独的线程调用与[类型]的方法.InvokeMember() [英] C# : Invoke a method with [Type].InvokeMember() in a separate Thread

查看:455
本文介绍了C#:在一个单独的线程调用与[类型]的方法.InvokeMember()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这code我在哪里调用运行的类的列表,我动态加载的dll的的方法:

I am using this code where I am invoking the run method of a List of classes that I loaded dynamically from dlls:

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 是调用运行推法每个类列表中。

The invokeMember is invoking the run methodof each of the classes in the list.

现在的我怎么能调用这个运行方法从 invokeMember 在一个单独的线程 ?所以,我要在运行为每个调用的方法独立的线程。

Now how can I invoke this run method from invokeMember in a separate Thread ? So that I'll have separate threads running for each of the invoked methods.

推荐答案

如果你知道你的所有动态加载的类实现运行,可能你只需要它们都实现IRunable,摆脱反射部分?

If you know that all your dynamically loaded types implement Run, could you just require they all implement IRunable and get rid of the reflection part?

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#:在一个单独的线程调用与[类型]的方法.InvokeMember()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆