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()

すべてのブランチから何かを返し、endinvokeを呼び出す必要があります。

于 2011-05-21T18:49:49.410 に答える