简体   繁体   中英

Multithreading in C# giving error with Invoke method

I'm facing a bit of problem, it's giving error "Cross-thread operation not valid" even though I'm using Invoke method.

Here's the code snipit.

Method to update log box

private void updateStatus(String msg)
    {
        if (logBox.InvokeRequired)
            logBox.Invoke((MethodInvoker)delegate()
            {
                logBox.SelectionStart = logBox.Text.Length;
                logBox.Text += "\n";
                logBox.Text += msg;
            });
        else
            logBox.SelectionStart = logBox.Text.Length;
            logBox.Text += "\n";
            logBox.Text += msg;
    }

And this Run method is being run by a thread.

private void Run()
    {
        int port;
        try
        {
            port = Int32.Parse(broadcastPortTextBox.Text);
        }
        catch (Exception ex)
        {
            MetroFramework.MetroMessageBox.Show(this, ex.Message);
            return;
        }

        updateStatus("Starting server at port: " + port.ToString());
        server = new HTTPServer.HTTPServer(port);
        server.Start();
    } //function

It runs fine for the first time but when I click stop, it gives an exception.

private void stopButton_Click(object sender, EventArgs e)
    {
        updateStatus("Stoping server");
        th.Abort();
        updateStatus("Server stoped!");
    }

I would try using the direct cast for the invoke. There's no need to check whether the invoke is required or not. If you invoke something it should always happen (in your context). Just remove the updateStatus( String msg) method so and try to cast your update like this:

void Run() {   
    // stuff     
    broadcastPortTextBox.Invoke(() => {
        port = Int32.Parse(broadcastPortTextBox.Text);
    });        
    // stuff..
    logBox.Invoke(() => {
        logBox.SelectionStart = logBox.Text.Length;
        logBox.Text += string.Format("{0}{1}", Environment.NewLine, "Your message text..");
    });
    // stuff..
}

Note: If you manipulate any non thread owned element use the invoke method. Otherwise you'll end up with exceptions (see ' broadcastPortTextBox ');

Edit: Accidently saved before I was done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM