我在运行时加载一些程序集,并使用反射(MethodInfo.Invoke)调用它们上的方法。
现在我想让这些调用是异步的。所以我正在考虑使用Delegate.BeginInvoke()。但是我不确定如何通过在运行时提供函数名来创建委托实例。(我看到的所有示例都在编译时解析了委托实例目标。)我有一个包含要调用的方法的MethodInfo对象。有没有办法做到这一点?
public void Invocation(Object[] inputObjs)
{
public delegate string DelegateMethodInfo(int num);
Assembly assm = Assembly.Load(assemblyName);
Type type = assm.GetType(className);
Type[] ctorParams = new Type[0];
Object[] objs = new Object[0];
ConstructorInfo ctorInf = type.GetConstructor(ctorParams);
Object classObj = ctorInf.Invoke(objs);
MethodInfo methodInf = type.GetMethod(methodName);
// Need asynchronous invocation.
//Object retObj = methodInf.Invoke(classObj, inputObjs);
DelegateMethodInfo del = new DelegateMethodInfo(???); // How to instantiate the delegate???
del.BeginInvoke((int)inputObjs[0], null, null);
}发布于 2009-11-05 03:40:34
只需使用一个封装methodInf.Invoke调用的lambda表达式即可。结果委托的类型为DelegateMethodInfo。
发布于 2009-11-05 03:39:22
你可以使用Delegate.CreateDelegate --但是你需要知道签名,这样你才能创建一个合适的委托类型。当您基本上只获得了MethodInfo时,这就有点棘手了:(更糟糕的是,没有用于异步执行的等价物Delegate.DynamicInvoke。
老实说,最简单的事情是启动一个调用该方法的新线程池作业:
ThreadPool.QueueUserWorkItem(delegate { methodInf.Invoke(classObj, inputObjs);});发布于 2009-11-05 03:47:25
这与其他答案类似,但您可以创建一个新的Func并将methodInf.Invoke方法分配给它。下面是一个例子
class Other
{
public void Stuff()
{ Console.WriteLine("stuff"); }
}
static void Main(string[] args)
{
var constructor = typeof(Other).GetConstructor(new Type[0]);
var obj = constructor.Invoke(null);
var method = typeof(Other).GetMethods().First();
Func<object, object[], object> delegate = method.Invoke;
delegate.BeginInvoke(obj, null, null, null);
Console.ReadLine();
}它所做的是创建一个与MethodInfo.Invoke签名匹配的Func<object, object[], object>类型的新变量。然后,它获取对对象上实际调用方法的引用,并将该引用保存在变量中。
由于Func<>是委托类型,因此可以使用BeginInvoke
https://stackoverflow.com/questions/1676084
复制相似问题