如何设置“中变量的值”;BeginInvoke“;C#中的委托函数?
我在不同的线程上有以下代码:如何设置“中变量的值”;BeginInvoke“;C#中的委托函数?,c#,delegates,begininvoke,C#,Delegates,Begininvoke,我在不同的线程上有以下代码: string sub = ""; this.BeginInvoke((Action)(delegate() { try { sub = LISTVIEW.Items[x].Text.Trim(); } catch { } })); MessageBox.Show(sub); 我想要的是获取“LISTVIEW.Items[x].Text.Trim();”的值并将其传递给“sub”。请注意,LIST
string sub = "";
this.BeginInvoke((Action)(delegate()
{
try
{
sub = LISTVIEW.Items[x].Text.Trim();
}
catch
{
}
}));
MessageBox.Show(sub);
我想要的是获取“LISTVIEW.Items[x].Text.Trim();
”的值并将其传递给“sub”。请注意,LISTVIEW控件位于主线程上。现在我如何才能做到这一点
enter code here
到
this.BeginInvoke((Func)(delegate()
stll需要从所有分支返回一些内容并调用end invoke。lambda语法只是创建委托的一种更好的方法。因此它仍然是委托。@ERMC2014您可以。这有点像转移视线。需要注意的是,BeginInvoke中的代码是异步wrt。调用者。将变量设置为post中的变量(使用适当的线程可见性控件)将起作用…但只有在EndInvoke之后才能保证。From:“在创建控件底层句柄的线程上异步执行委托。”感谢您提供的解决方案和解释。其工作方式与charm:)如果您要开始Invoke,EndInvoke,那么您可以简单地将原始代码更改为使用Invoke。
Func<string> foo = () =>
{
try
{
return LISTVIEW.Items[x].Text.Trim();
}
catch
{
// this is the diaper anti-pattern... fix it by adding logging and/or making the code in the try block not throw
return String.Empty;
}
};
var ar = this.BeginInvoke(foo);
string sub = (string)this.EndInvoke(ar);
this.BeginInvoke((Action)(delegate()
this.BeginInvoke((Func<String>)(delegate()