Question

I got a problem with my textbox.
I have a class that represents the GUI thread and a class for the worker thread that does some networking stuff and then has to add the log to the textbox in the GUI thread so you can see what is happening in the background.
However, I have the problem that nothing happens on the GUI, only the debug information that addLine() was called is in the console.
The method addLine() that should add the log gets called but it seems like AppendText() just does nothing.
I am pretty sure this has to do something with the threads but I am not sure how I shall solve this.

Here is the code:

Worker Thread:

    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 Thread:

    // 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();
    }

I tried to do some Invoke stuff already but failed at using it properly.
The GUI either locked itself or it just continued to do nothing.

Était-ce utile?

La solution

You can't take to a winforms UI if you aren't on the UI thread. Try:

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

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

which will bump it onto the UI thread.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top