2011-05-27 17 views
0

私はC#で書かれたWindowsモバイルアプリケーションを持っています。イベントが発生したときにダイアログを更新したいここでは、コードは次のとおりです。Windows Mobile 6 UIの更新の問題

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

スレッド間の問題が発生する可能性があります。関数の先頭にあるthis.InvokeRequiredをチェックし、それに応じて反応すると、関数の安全性が確実に向上します。このようなもの:

public void ServerStateChanged()   
{ 
    if(this.InvokeRequired) 
    { 
     this.Invoke(new delegate 
     { 
      ServerStateChanged(); 
     } 
     return; 
    } 

    if (this.Focused)     
    {      
     this.noConnectionsLL.Text = this.tcpServer.ClientsCount.ToString(); 
    }    
}    
2

または以下のようなlamba方法。私がControl.BeginInvokeを使用して批判を受ける前に、BeginInvokeはスレッドセーフであり、完全に非同期です(呼び出しはUIイベントキューに更新を渡します)。

public void ServerStateChanged() 
    { 
     this.BeginInvoke((Action)(() => 
     { 
      if (this.Focused) 
      { 
       this.noConnectionsLL.Text = this.tcpServer.ClientsCount.ToString(); 
      }  
     })); 
    }