c# - C# 中的多线程使用 Invoke 方法给出错误

标签 c# multithreading

我遇到了一些问题,即使我使用 Invoke 方法,它也会给出错误“跨线程操作无效”。

这是代码片段。

更新日志框的方法

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;
    }

这个 Run 方法正在由一个线程运行。

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

第一次运行正常,但是当我单击“停止”时,出现异常。

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

最佳答案

我会尝试使用直接转换进行调用。无需检查是否需要调用。如果你调用某些东西,它应该总是发生(在你的上下文中)。只需删除 updateStatus(String msg) 方法,然后尝试像这样转换更新:

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..
}

注意:如果您操作任何非线程拥有的元素,请使用 invoke 方法。否则,您最终会遇到异常(请参阅“broadcastPortTextBox”);

编辑:在完成之前意外保存。

关于c# - C# 中的多线程使用 Invoke 方法给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31716971/

相关文章:

c# - ASP.NET 生成的输出不受 JQuery/Javascript 的影响

c# - Distinct 在 Entity Framework 上不起作用

c# - 在 C# 中,分贝的幅度总是返回 NaN

c++ - 使用 boost 线程只能工作一半

java - 具有同步块(synchronized block)的 Java 内存模型中单例的弱点

c# - 使用 Regex.Match 静态方法查找从特定位置开始的匹配项

c# - 如何使用该结构的元素在数组中找到该结构?

c++ - 无法初始化线程 vector

python - 多处理和多线程

Python Queue.get(block=False) 与非空队列。它可以引发Queue.empty吗?