-1

重複の可能性:
クロススレッド操作が無効です: コントロールが作成されたスレッド以外のスレッドからアクセスされました

以下は、私が作成した、RichTextControl からテキストを取得して返すメソッドです。

    /** @delegate */
    private delegate string RichTextBoxObtainContentsEventHandler();

    private string ObtainContentsRichTextBox()
    {

        if (richtxtStatus.InvokeRequired)
        {
            // this means we're on the wrong thread!  
            // use BeginInvoke or Invoke to call back on the 
            // correct thread.
            richtxtStatus.Invoke(
                new RichTextBoxObtainContentsEventHandler(ObtainContentsRichTextBox)
                );
            return richtxtStatus.Text.ToString();
        }
        else
        {

            return richtxtStatus.Text.ToString();
        }
    }

ただし、これを実行しようとすると、次の例外が発生します: Cross-thread operation not valid: コントロール 'richtxtStatus' は、それが作成されたスレッド以外のスレッドからアクセスされました。

上記のコードを変更して内容を返すにはどうすればよいですか?

4

1 に答える 1

4

問題は、間違ったスレッドでテキスト ボックスにアクセスしていることです。Invoke()単に呼び出して結果を無視し、最初に回避しようとしていたことを実行するのではなく、の結果を返す必要があります。また、イベント ハンドラーでラップする必要はありません。現在のメソッドをもう一度呼び出すだけです。

if (richtxtStatus.InvokeRequired)
{
    // this means we're on the wrong thread!  
    // use BeginInvoke or Invoke to call back on the 
    // correct thread.
    string text = (string)richtxtStatus.Invoke(ObtainContentsRichTextBox);
    return text;
}

最後に、.Textは既に文字列であるため、呼び出す必要はありません.ToString()。直接返品可能です。

于 2012-04-10T22:24:33.357 に答える