2012-10-16 60 views
0

我正在研究串口相關的應用程序。在使用DataReceived事件SerialPort我需要與接收的字節更新文本框:在終止任務之前正確使用InvokeRequired

private void Connection_DataReceived(object sender, SerialDataReceivedEventArgs e) 
{ 
    ledReceive.On = true; 

    var data = Connection.ReadExisting(); 

    _readBuffer.Add(data); 
    Invoke(new EventHandler(AddReceivedPacketToTextBox));  
} 

所以我用Invoke更新文本框。但是有一個很大的問題。當我嘗試關閉連接時,我的用戶界面被凍結,我認爲這是因爲Invoke或許正在做些什麼。

一位朋友說我應該使用RequiredInvoke,但我不知道他真的是什麼。如何關閉連接而不會搞亂調用和UI線程?

這裏是我的關閉方法:

private void DisconnectFromSerialPort() 
{ 
    if (Connection != null && Connection.IsOpen) 
    { 
     Connection.Close(); 
     _receivedPackets = 0; //reset received packet count 
    } 
} 

回答

1

我不能完全肯定,但我猜,是更新UI線程被刪除,當你關閉你的連接,這可以解釋爲什麼它凍結。但是我不能確定沒有挖掘你的所有代碼。

InvokeRequired返回true,如果嘗試訪問您的元素的線程不是本機到您的UI。或者如果你喜歡MS交代:

// Summary: 
    //  Gets a value indicating whether the caller must call an invoke method when 
    //  making method calls to the control because the caller is on a different thread 
    //  than the one the control was created on. 
    // 
    // Returns: 
    //  true if the control's System.Windows.Forms.Control.Handle was created on 
    //  a different thread than the calling thread (indicating that you must make 
    //  calls to the control through an invoke method); otherwise, false. 

而且基本實現:

public void ReceiveCall() 
    { 
     if (this.InvokeRequired) 
     { 
      this.Invoke(new CallDelegate(ReceiveCall), new object[] { }); 
      return; // Important to not continue on this method. 
     } 

     // Whatever else this function is suppose to do when on the correct thread. 
    } 

的調用應該是你的功能所做的第一件事,以防止線程在UI深進入。現在,如果連接本身被確定爲處於UI線程的流水線中,那麼它可能不會觸發「InvokeRequired」。防止這種情況發生的一種方法是手動創建一個線程,以更新未綁定到連接的UI。

我有一個更新多個UI元素呈現的時鐘類似的問題。時鐘可以正常工作,但會「掛起」,直到所有界面都完成渲染,這對於大量UI來說意味着它會跳過下一個勾號。

 Thread updateUI = new Thread(updateUIDelegate); 
    updateUI.Start(); 

這樣,我的時鐘(或你的連接)就會啓動一個獨立的線程來完成它自己的工作。您可能還需要檢查Monitor類或lock關鍵字,以防止使用相同變量衝突線程或多個線程。

編輯:或者你也可以閱讀在真棒答案,這可能更有意義比我:What causes my UI to freeze when closing a serial port?

+0

謝謝回答。不知道爲什麼我有2個相同的問題! –