从功能的C#返回值调用线程 [英] C# Return value from function invoked in thread
问题描述
我有一个使用调用其他线程调用消息功能的计算线程函数,我想,在计算线程从消息功能获得价值(值类型,像整数)。我怎样才能做到这一点?
的问题是,我以后调用(...)仍然得到变量x的原值和我预计的15
$ B值$ b
委托无效mes_del(对象参数);
无效MyThreadFunc()
{
...
INT X = 5;
对象[] = PARMS新的对象[] {X};
调用(新mes_del(MessageFunc),(对象)PARMS);
:
}
无效MessageFunc(对象结果)
{
INT解析度= 15;
(导致作为对象[])[0] =资源;
}
我试着喜欢使用对象[],对象没有成功参数的一些方法。我虽然装箱/拆箱操作应该发生在这种情况下,但他们没有。
我应该使用辅助型像它在.NET事件模式下完成,并创建一个像
类持有人
{
公众诠释点¯x调解对象;
}
INT X = 5;
对象[] = PARMS新的对象[] {X};
什么上面的代码的作用是声明一个局部变量,分配值5,然后构造一个包含一个元素是一个的复制<对象[]
阵列/ em>的本地变量。
然后,通过这个的阵列的到你的调用
电话。
我想你会发现是调用
被调用后, PARMS [0]
是15但这并不影响 X
,这实际上有一个 REF传递
参数的任何的方法能够。修改其本地值
我见过之前完成是这样的:
类箱< T>
{
公众的T值{搞定;组; }
}
然后,你可以这样做:
无效MyThreadFunc()
{
变种x =新盒和LT; INT> {值= 5};
//顺便说一句,真的没有理由去定义自己的
// mes_del委托类型。
调用(新动作<盒及LT; INT>>(MessageFunc),X);
}
无效MessageFunc(盒及LT; INT> ARG)
{
arg.Value = 15;
}
I have a calculating thread function which invokes message function from other thread using Invoke and I want that calculating thread to get value(of valuetype, like integer) from that message function. How can I do this?
The problem is that I still get old value of x variable after Invoke(...) and I expect 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 like using object[], object as parameters with no success. I though boxing/unboxing operations should occur in such a case but they don't. Should I use auxiliary type like it is done in .NET event mode and create mediator object like class holder { public int x; }
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;
}
这篇关于从功能的C#返回值调用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!