C # Return value from function called in thread

I have a stream calculation function that calls a message function from another stream using Invoke, and I want the stream calculation to get a value (valueetype, for example integer) from this message function. How can i do this?

The problem is that I still get the old value of the x variable after Invoke (...), and I expect a value of 15

delegate void mes_del(object param);

void MyThreadFunc()
{
...
int x = 5;
object [] parms = new object []{x};
Invoke(new mes_del(MessageFunc), (object)parms);
...
}

void MessageFunc(object result)
{
   int res = 15;
   (result as object[])[0] = res;
}

I tried some approaches, such as using object [], object as parameters without success. I, although boxing / unpacking operations should take place in this case, but they do not. Should I use a helper type, as is done in the .NET event mode, and create a mediator object, for example, the owner of the class {public int x; }

0
4
int x = 5;
object [] parms = new object []{x};

, , , 5, object[], , .

Invoke.

, , Invoke parms[0] 15. x, ref .


, , :

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

:

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

    // By the way, there 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;
}
+4

Control.Invoke Windows Forms? , , :

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

, , , x , ( ). , , .

+1

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

, .NET 4.0 System.Threading.Tasks

, , . , WriteLine .

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

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

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

.

0

All Articles