我想知道如何將通過串口接收的數據鏈接到在主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;
}
你的代碼甚至不會編譯,你的catch塊*在你的try塊中,這是無效的語法。 –
您是否正在編寫WPF或WinForms UI?在任何情況下,出於任何原因暫停UI線程似乎都不是一個好主意。聽起來就像您試圖在應用程序上實施「半雙工」通信模式,而串行端口客戶端應用程序通常不需要這種模式。這是一個[鏈接](http://social.msdn.microsoft.com/Forums/en/wpf/thread/faa4f9dd-db1b-46fb-8b90-f71b2836b5dc),無論如何它可能有一些幫助。 –
對不起,這是無效的語法,我不正確地剪切和粘貼我的代碼,錯過了一個}。 我正在使用Windows窗體GUI,感謝您的鏈接! :) – Bela