简体   繁体   中英

Does SerialPort receive data on its own thread?

Let's say we have the follwing code:

SerialPort port = new SerialPort("COM2", 115200); 
port.Open();
//
Thread.Sleep(5000);
//
if (port.BytesToRead > 0)
{
   Console.WriteLine("Bytes in buffer: " + port.BytesToRead.ToString());
}

If during those 5000 milliseconds in which the thread is blocked, 5 bytes were sent to the serial port, would the code print that there are 5 bytes in the buffer? Or would it not start receiving until the Thread.Sleep returns?

Thanks

Communication on hardware devices, such as HDDs, network ports, and yes, serial ports, are performed using an I/O completion thread, managed by the ThreadPool. So, the short answer to your question is that data should be received by the port even when your program is not actively running and listening for it. Once your thread wakes up, it will ask the port how many bytes are in the buffer, and it will respond saying it had 5 more bytes then before you slept your thread.

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