简体   繁体   English

线程不读

[英]Thread doesn't read

I'm writing C# code for use with Unity3D in order to read from a serial port. 我正在编写用于Unity3D的C#代码,以便从串行端口读取。 This is done with another thread. 这是通过另一个线程完成的。 The reading thread hangs when calling the SerialPort.Read method. 调用SerialPort.Read方法时,读取线程挂起。 The reading thread class is as follows: 阅读线程类如下:

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();}
    }
}

It is called like this: 它的名称如下:

workaround = new Serial_Port_Reader(input, Data.bytes);
reader = new Thread(new ThreadStart(workaround.read));
reader.Start();

If the thread is already active it halts at "C" and remains there even when I send data. 如果线程已经处于活动状态,则即使在我发送数据时,它也会在“ C”处停止并保持在那里。 If I start the thread in the middle of receiving data, it will work as it should (ie it will read one character) and then halt at "C" on the next loop through. 如果我在接收数据的中间启动线程,它将按应有的方式工作(即它将读取一个字符),然后在下一个循环中停在“ C”处。

I am trying to get it to continuously read in data. 我试图使其不断读取数据。 Why does it stop at "C" and not continue under ordinary circumstances? 为什么在“ C”处停止,而在通常情况下不继续?

Does it throw an exception? 它会引发异常吗? Did you sent enough bits? 您发送的位够吗? read() may block until you don't have read count bits. read()可能会阻塞,直到您没有读取count位为止。

msdn: msdn:

Because the SerialPort class buffers data, and the stream contained in the BaseStream property does not, the two might conflict about how many bytes are available to read. 因为SerialPort类会缓冲数据,而BaseStream属性中包含的流不会缓冲数据,所以两者可能在可读取的字节数方面发生冲突。 The BytesToRead property can indicate that there are bytes to read, but these bytes might not be accessible to the stream contained in the BaseStream property because they have been buffered to the SerialPort class. BytesToRead属性可以指示存在要读取的字节,但是这些字节可能无法被BaseStream属性中包含的流访问,因为它们已被缓冲到SerialPort类中。

The Read method does not block other operations when the number of bytes read equals count but there are still unread bytes available on the serial port. 当读取的字节数等于计数,但串行端口上仍有可用的未读字节时,Read方法不会阻止其他操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM