采取方法System.Windows.Forms.Control.Invoke(Delegate方法)
为什么会出现编译时错误:
string str = "woop";
Invoke(() => this.Text = str);
// Error: Cannot convert lambda expression to type 'System.Delegate'
// because it is not a delegate type
Run Code Online (Sandbox Code Playgroud)
但这很好用:
string str = "woop";
Invoke((Action)(() => this.Text = str));
Run Code Online (Sandbox Code Playgroud)
当方法需要普通代表时?
我有这个小方法应该是线程安全的.一切正常,直到我希望它具有回报价值而不是虚空.如何在调用BeginInvoke时获得返回值?
public static string readControlText(Control varControl) {
if (varControl.InvokeRequired) {
varControl.BeginInvoke(new MethodInvoker(() => readControlText(varControl)));
} else {
string varText = varControl.Text;
return varText;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我想在这种情况下让BeginInvoke不是nessecary,因为我需要来自GUI的值才能继续线程.所以使用Invoke也很好.只是不知道如何在以下示例中使用它来返回值.
private delegate string ControlTextRead(Control varControl);
public static string readControlText(Control varControl) {
if (varControl.InvokeRequired) {
varControl.Invoke(new ControlTextRead(readControlText), new object[] {varControl});
} else {
string varText = varControl.Text;
return varText;
}
}
Run Code Online (Sandbox Code Playgroud)
但不知道如何使用该代码获得价值;)
我在google/here上看到很多线程在UPDATING来自另一个线程的UI元素.
如果我想获得复选框的值,该怎么办?
我能不做任何特别的事情吗?