[英]Thread doesn't read
我正在編寫用於Unity3D的C#代碼,以便從串行端口讀取。 這是通過另一個線程完成的。 調用SerialPort.Read方法時,讀取線程掛起。 閱讀線程類如下:
public class Serial_Port_Reader {
private SerialPort port;
private byte[] data;
private int bytes;
public Serial_Port_Reader(SerialPort in_port, int in_bytes) {
port = in_port;
bytes = in_bytes;
data = new byte[bytes];
}
public void read() {
try {
while(true) {
IO.log.Add("A");
data = new byte[bytes];
IO.log.Add("C");
port.Read(data, 0, 1);
IO.log.Add("Data Received: "+DateTime.Now.ToString());
Data.parse(data);
IO.log.Add("D");
port.DiscardInBuffer();
}
}
catch(ThreadAbortException e) {IO.log.Add("Abort:"+e.Message);}
catch(IOException e) {IO.log.Add("IO:"+e.Message);}
catch(Exception e) {IO.log.Add(e.Message);}
finally {if(port.IsOpen) port.Close();}
}
}
它的名稱如下:
workaround = new Serial_Port_Reader(input, Data.bytes);
reader = new Thread(new ThreadStart(workaround.read));
reader.Start();
如果線程已經處於活動狀態,則即使在我發送數據時,它也會在“ C”處停止並保持在那里。 如果我在接收數據的中間啟動線程,它將按應有的方式工作(即它將讀取一個字符),然后在下一個循環中停在“ C”處。
我試圖使其不斷讀取數據。 為什么在“ C”處停止,而在通常情況下不繼續?
它會引發異常嗎? 您發送的位夠嗎? read()
可能會阻塞,直到您沒有讀取count
位為止。
因為SerialPort類會緩沖數據,而BaseStream屬性中包含的流不會緩沖數據,所以兩者可能在可讀取的字節數方面發生沖突。 BytesToRead屬性可以指示存在要讀取的字節,但是這些字節可能無法被BaseStream屬性中包含的流訪問,因為它們已被緩沖到SerialPort類中。
當讀取的字節數等於計數,但串行端口上仍有可用的未讀字節時,Read方法不會阻止其他操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.