C# Return value from function invoked in thread

老子叫甜甜 提交于 2019-11-28 14:48:35
int x = 5;
object [] parms = new object []{x};

What the above code does is declare a local variable, assign it the value 5, then construct an object[] array containing one element which is a copy of that local variable.

You then pass this array into your Invoke call.

I think what you'll find is that after Invoke is called, parms[0] is 15. But this does not affect x, which would actually have to be passed as a ref parameter for any method to be able to modify its local value.


What I've seen done before is something like this:

class Box<T>
{
    public T Value { get; set; }
}

Then you could do:

void MyThreadFunc()
{
    var x = new Box<int> { Value = 5 };

    // By the way, there's really no reason to define your own
    // mes_del delegate type.
    Invoke(new Action<Box<int>>(MessageFunc), x);
}

void MessageFunc(Box<int> arg)
{
    arg.Value = 15;
}

Are you talking about Control.Invoke from Windows Forms? If yes, the method can also return a result, so you can write:

delegate int mes_del(int param);

void MyThreadFunc() {
  int x = 5;
  object [] parms = new object []{x};
  x = (int)Invoke(new mes_del(MessageFunc), x);
  // you'll get a new value of 'x' here (incremented by 10)
}

int MessageFunc(int result) {
  return result + 10;
}

Your code probably didn't work, because you were accessing x instead of picking a new value from the array (that should be modified). However, using an overload that returns a new value should be a much clearer solution.

Just return value from method

void MyThreadFunc()
{
...
int x = 5;
object [] parms = new object []{x};
var callResult = (int)Invoke((Func<object,int>)MessageFunc, (object)parms);
...
}

int MessageFunc(object result)
{
   int res = 15;
   return res;
}

Perhaps the best answer to your question is in .NET 4.0 System.Threading.Tasks

Here the main thread is blocked till the Result is returned by the method called on the other thread. If the result is already returned by the main thread reaches the WriteLine there is no blocking.

Task task = Task.Factory.StartNew(SomeMethod);
Console.WriteLine(task.Result);

public static string SomeMethod()
{
    return "Hello World";
}

OR

Task task = Task.Factory.StartNew(() => { return "Hello World"; } );
Console.WriteLine(task.Result);

Check this blog for more interesting samples.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!