Search code examples
c#reflectiondelegatesinvokemethodinfo

Asynchronous runtime method invocation


I am loading some assemblies at run time and invoking methods on them using Reflections (MethodInfo.Invoke).

Now I want to make these calls asynchronous. So I am thinking of using Delegate.BeginInvoke(). But I am not sure how to create delegate instance by providing function name at run-time. (All examples I see have delegate instance target resolved at compile time itself.) I have a MethodInfo object containing the method to be invoked. Is there a way to do this?

   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);
    }

Solution

  • Just use a lambda expression that wraps the call to methodInf.Invoke. The resulting delegate is of type DelegateMethodInfo.