我有一个用C#编写的Windows移动应用程序,它有更多的对话框。我想在触发事件时更新对话框。这是代码:
public void ServerStateChanged()
{
// update the interface
try
{
if (this.Focused)
{
this.noConnectionsLL.Text = this.tcpServer.ClientsCount.ToString();
}
}
catch (Exception exc)
{
}
}
代码可以运行几次,但后来我使用此堆栈跟踪得到System.NotSupportedException
:at Microsoft.AGL.Common.MISC.HandleAr()\r\nat System.Windows.Forms.Control.get_Focused()\r\nat DialTester.Communication.TCPServerView.ServerStateChanged()\r\nat ...
触发事件的线程是否重要?因为我无法弄清楚问题是什么,为什么它会工作几次然后崩溃。
答案 0 :(得分:2)
或lamba方式如下。在我被批评使用Control.BeginInvoke之前,BeginInvoke是线程安全的并且是完全异步的(调用会将更新放在UI事件队列中)。
public void ServerStateChanged()
{
this.BeginInvoke((Action)(() =>
{
if (this.Focused)
{
this.noConnectionsLL.Text = this.tcpServer.ClientsCount.ToString();
}
}));
}
答案 1 :(得分:0)
这可能是一个跨线程的问题。检查功能顶部的this.InvokeRequired
并做出相应的反应肯定会提高功能的安全性。像这样:
public void ServerStateChanged()
{
if(this.InvokeRequired)
{
this.Invoke(new delegate
{
ServerStateChanged();
}
return;
}
if (this.Focused)
{
this.noConnectionsLL.Text = this.tcpServer.ClientsCount.ToString();
}
}