2

テキストボックスに問題が発生しました。
GUIスレッドを表すクラスと、ネットワーク関連の処理を行うワーカースレッドのクラスがあり、バックグラウンドで何が起こっているかを確認できるように、GUIスレッドのテキストボックスにログを追加する必要があります。
ただし、GUIで何も起こらず、addLine()が呼び出されたデバッグ情報のみがコンソールに表示されるという問題があります。
ログを追加する必要があるメソッドaddLine()が呼び出されますが、AppendText()は何もしないようです。
私はこれがスレッドで何かをしなければならないことをかなり確信していますが、これをどのように解決するかはわかりません。

コードは次のとおりです。

ワーカースレッド:

    Form1 form = new Form1();
    // This method gets called in the worker thread when a new log is available
    private void HandleMessage(Log args)
    {
        // Using an instance of my form and calling the function addLine()
        form.addLine(args.Message);
    }

GUIスレッド:

    // This method gets called from the worker thread
    public void addLine(String line)
    {
        // Outputting debug information to the console to see if the function gets called, it does get called
        Console.WriteLine("addLine called: " + line);
        // Trying to append text to the textbox, console is the textbox variable
        // This pretty much does nothing from the worker thread
        // Accessing it from the GUI thread works just fine
        console.AppendText("\r\n" + line);

        // Scrolling to the end
        console.SelectionStart = console.Text.Length;
        console.ScrollToCaret();
    }

私はすでにいくつかのInvokeを実行しようとしましたが、正しく使用できませんでした。
GUIはそれ自体をロックするか、何もしませんでした。

4

1 に答える 1

8

UIスレッドを使用していない場合、WinFormsUIを使用することはできません。試す:

console.Invoke((MethodInvoker)delegate {
    console.AppendText("\r\n" + line);

    console.SelectionStart = console.Text.Length;
    console.ScrollToCaret();
});

UIスレッドにぶつかります。

于 2012-07-22T19:14:13.343 に答える