0

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

4

1 に答える 1

1

基本的に 2 つのオプションがあります。MethodInfo.Invoke を同期的に呼び出して、結果を待ちます。または、呼び出しが完了したら呼び出されるようにコールバック メソッドを設定します。リンク先の例からの拡張:

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

呼び出しが完了したときに呼び出されるデリゲートを受け取る追加のパラメーターを追加しました。次に、次のように使用できます。

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);
}
于 2011-01-25T16:11:36.813 に答える