2011-08-23 89 views
2

我想知道如何將通過串口接收的數據鏈接到在主UI中調用它的函數。如何將SerialPort接收到的數據鏈接到主UI線程的讀取函數?

我想要用戶界面從串口發出數據,然後掛起線程或等待,直到數據通過串口線程接收,然後繼續主UI線程。

我被告知,thread.suspend()不是一個安全的函數使用,我與thread.resume一起嘗試,但失敗。

我應該看看lock/mutex嗎?

或EventWaitHandles?

我徹底困惑!我不熟悉線程,所以任何幫助將不勝感激!謝謝。下面

代碼:

公共靜態INT SerialCOM_Read(UINT tRegisterAddress,出來的byte [] tRegisterValue,UINT爲nbytes) {

 int retVal = 1; 

     tRegisterValue = new byte[nBytes]; 

    byte[] nBytesArray = new byte[4]; 

     NBytes = nBytes; 


     try { 

      ReadFunction = true; 
      YetToReceiveReadData = true; 
     byte[] registerAddress = BitConverter.GetBytes(tRegisterAddress); 

     int noOfBytesForRegAdd = 1; 

     if (registerAddress[3] > 0) noOfBytesForRegAdd = 4; 
     else if (registerAddress[2] > 0) noOfBytesForRegAdd = 3; 
     else if (registerAddress[1] > 0) noOfBytesForRegAdd = 2; 

     nBytesArray = BitConverter.GetBytes(nBytes); 
     { 

     Append_Start(); 
     Append_Operation_with_NoOfBytesForRegAdd(OPERATION.I2C_READ, noOfBytesForRegAdd); 
     Append_RegAdd(noOfBytesForRegAdd, tRegisterAddress); 
     Append_NoOfBytesOfData(nBytesArray); 

     Send_DataToWrite(); 

    //Need to Suspend Thread here and Continue once the 
    //ReadData[i] global variable has been assigned. 

    for(int i=0; i<nBytes; i++) 
tRegisterValue[i] = ReadData[i]; 
    } 
     catch(Exception ex) {} 

     return retVal; 

}

+1

你的代碼甚至不會編譯,你的catch塊*在你的try塊中,這是無效的語法。 –

+0

您是否正在編寫WPF或WinForms UI?在任何情況下,出於任何原因暫停UI線程似乎都不是一個好主意。聽起來就像您試圖在應用程序上實施「半雙工」通信模式,而串行端口客戶端應用程序通常不需要這種模式。這是一個[鏈接](http://social.msdn.microsoft.com/Forums/en/wpf/thread/faa4f9dd-db1b-46fb-8b90-f71b2836b5dc),無論如何它可能有一些幫助。 –

+0

對不起,這是無效的語法,我不正確地剪切和粘貼我的代碼,錯過了一個}。 我正在使用Windows窗體GUI,感謝您的鏈接! :) – Bela

回答

0

如果你要阻止用戶界面線程,那麼使用DataReceived事件沒有意義。只需直接調用SerialPort.Read/Line()即可。這可能會導致用戶界面響應速度的延遲通常是不合需要的,但這樣做肯定要容易得多。

+0

非常感謝!是的,這正是我需要的! :) – Bela

0

只需創建一個委託並使用它將數據發送到可以處理從串行端口收到的數據的方法。我的用例是我通過端口發送數據,我不知道什麼時候得到響應,可能是任何時間,但當時數據來了我應該能夠得到它並處理它,所以我做了以下。認爲這是你可能想要的

Public Delegate Sub recieveDelegate() 

Private Sub datareceived1(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPrt.DataReceived 

    buffer = buffer & SerialPrt.ReadExisting() 

    If InStr(1, rxbuff, EOF) > 0 Then 
     Rxstring = rxbuff 
     rxbuff = "" 
     BeginInvoke(New recieveDelegate(AddressOf recieveHandlingMethod), New Object() {}) 
    End If 
End Sub 

只處理你收到的數據在接收處理方法。

+0

感謝劍魚,我不確定如何創建一個委託,所以這個信息真的也有幫助! :) – Bela