Windows Mobile 6 UI更新问题

时间:2011-05-27 14:16:30

标签: c# user-interface windows-mobile

我有一个用C#编写的Windows移动应用程序,它有更多的对话框。我想在触发事件时更新对话框。这是代码:

 public void ServerStateChanged()
        {
            // update the interface
            try
            {
                if (this.Focused)
                {
                    this.noConnectionsLL.Text = this.tcpServer.ClientsCount.ToString();
                }
            }
            catch (Exception exc)
            {
            }
        }

代码可以运行几次,但后来我使用此堆栈跟踪得到System.NotSupportedExceptionat Microsoft.AGL.Common.MISC.HandleAr()\r\nat System.Windows.Forms.Control.get_Focused()\r\nat DialTester.Communication.TCPServerView.ServerStateChanged()\r\nat ...

触发事件的线程是否重要?因为我无法弄清楚问题是什么,为什么它会工作几次然后崩溃。

2 个答案:

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