我遇到了一些问题,即使我使用 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/