[英]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.