简体   繁体   中英

Thread doesn't read

I'm writing C# code for use with Unity3D in order to read from a serial port. This is done with another thread. The reading thread hangs when calling the SerialPort.Read method. 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. 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.

I am trying to get it to continuously read in data. Why does it stop at "C" and not continue under ordinary circumstances?

Does it throw an exception? Did you sent enough bits? read() may block until you don't have read count bits.

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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