2013-12-19 53 views
1

我有一个C#表单,我使用了MSDN上详述的Invoke方法从另一个线程与之交谈。调用主线程的工作方法,和这里的基本结构的一个片段:如何从C#中的异步调用返回值?

// In the main thread: 
public void doCommand(int arg, out int ret) { 
    ret = arg + 1; 
} 

// On another thread: 
public delegate void CmdInvoke(int arg, out int ret); 

public void execute() { 
    CmdInvoke d = new CmdInvoke(Program.form.doCommand); 
    int a = 0; 
    int b = 0; 
    Program.form.Invoke(d, new object[] { a, b }); 

    // I want to use b now... 
} 

如上所述,我现在要返回参数b回调用线程。目前,b始终为0。我读过,也许我需要使用BeginInvokeEndInvoke,但我有点困惑说实话我怎么能在b?我不介意它是out参数还是return,我只是想要它!

+1

你能用'Func '吗? –

+0

您正在使用错误的工具。说明你使用的版本。 C#5? –

+0

为什么你首先要做这件事?如果你有一个后台线程做一些工作,并且你调用Invoke来更新UI,为什么UI更新需要将信息发送回长时间运行的任务?首先这是一个非常不寻常的要求。 – Servy

回答

1

可以以这样的方式得到doCommand更新值(作为out参数在普通方式与return没有返回新值):

// In the main thread: 
public int doCommand(int arg) { 
    return arg + 1; 
} 

// On another thread: 
public delegate int CmdInvoke(int arg); 

public void execute() { 
    CmdInvoke d = new CmdInvoke(Program.form.doCommand); 
    int a = 0; 
    int b = 0; 
    b = (int)Program.form.Invoke(d, new object[] { a }); 
    // Now b is 1 
} 

out参数不起作用,因为当你将b放入数组object[]副本b实际上是包含在数组中(因为boxing)。因此,方法doCommand更改该复制不是原始b变量。

+0

像梦一样工作,谢谢! –