1

我在不同的线程上有这个代码:

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
4

1 回答 1

2
        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);

当然,您需要小心使用 EndInvoke,因为它会导致死锁。

如果您更喜欢委托语法,您也可以更改

this.BeginInvoke((Action)(delegate()

this.BeginInvoke((Func<String>)(delegate()

你需要从所有分支返回一些东西并调用结束调用。

于 2011-05-21T18:49:49.410 回答