سؤال

I have been looking through the other questions on the site and have found this post.

stack overflow original post

Ben Voigts answer is very useful and I believe I have it working in my system.

The issue I have is that in some cases I will need a value to be returned from the method invocation.

I was going to just leave a comment on that post but my rep isnt high enough to leave comments.

Hopefully either Ben will see this post or someone else will be able to extend his answer to include how to return a value.

Please let me know if there is any other information you require.

Kind Regards

Ash

هل كانت مفيدة؟

المحلول

You basically have two options. Either you call the MethodInfo.Invoke synchronously and wait for the result. Or you set up a callback method to get called once the invocation is complete. Extending from the example you linked to:

public void InvokeOnNewThread(MethodInfo mi, object target, Action<object> callback, params object[] parameters)
{
     ThreadStart threadMain = delegate () 
        { 
            var res = mi.Invoke(target, parameters); 
            if(callback != null)
                callback(res);
        };
     new System.Threading.Thread(threadMain).Start();
}

I added an extra parameter which takes a delegate that will get called when the invocation is done. Then you can use it this way:

void Main()
{
    var test = new Test();
    var mi = test.GetType().GetMethod("Hello");
    InvokeOnNewThread(mi, test, GetResult);


    Thread.Sleep(1000);
}

public void GetResult(object obj) 
{
    Console.WriteLine(obj);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top