![](/img/trans.png)
[英]How do I call asynchronous method returning void from synchronous method in C# and be sure async method is finished?
[英]How do I return values from an asynchronous call in C#?
我有一個C#表單,可以使用MSDN上詳細介紹的Invoke
方法與另一個線程進行對話。 在主線程上調用該方法可以正常工作,這是基本結構的一部分:
// 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
。 我讀過,也許我需要使用BeginInvoke
和EndInvoke
,但老實說我有點困惑,我怎么能到達b
? 我不在乎它是out
參數還是return
,我只是以某種方式想要它!
您可以通過以下方式從doCommand
中獲取更新后的值(以常規方式返回新值,而return
不作為out
參數):
// 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
變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.