I have this code on different thread:
string sub = "";
this.BeginInvoke((Action)(delegate()
{
try
{
sub = LISTVIEW.Items[x].Text.Trim();
}
catch
{
开发者_如何转开发 }
}));
MessageBox.Show(sub);
what I want is to get the value of "LISTVIEW.Items[x].Text.Trim();
" and pass it to "sub". please note that the LISTVIEW control is on the main thread. now how can I accomplish this?
enter code here
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);
You, of course, need to be a bit careful with EndInvoke because it can cause deadlocks.
if you prefer delegate syntax you can also change
this.BeginInvoke((Action)(delegate()
to
this.BeginInvoke((Func<String>)(delegate()
you stll need to return something from all branches and call end invoke.
精彩评论