Serial Port Complete - Latest Microcontroller projects

(lily) #1
Managing Ports and Transfers in .NET

 


When sending data, the application should prevent or minimize timeouts and
prevent buffer overflows. An application can perform write operations in a sep-
arate thread to avoid blocking the application’s thread. This section shows strat-
egies for accomplishing these tasks.

8 
1  


The likelihood of a timeout increases when an application transfers large quan-
tities of data, uses a slow bit rate, or uses flow control.
When a write operation times out, any data that was waiting to transmit in that
operation is lost. Data queued to the port in subsequent write operations
remains in the buffer. Setting WriteTimeout to InfiniteTimeout ensures that
write operations never time out, but a write operation could wait forever if the
remote computer hangs and doesn’t allow the data to transmit. Applications
that need to send large blocks of data can use multiple write operations to send
the data in chunks with generous but finite timeouts. Writing data in smaller
chunks also helps prevent buffer overflows.


 
6  
  


Using the standard Windows drivers, a write operation to a physical COM port
will block until the UART has transmitted all of the data or a timeout has
occurred. While the data is transmitting or waiting to transmit, the application’s
thread can’t perform other operations, including responding to user input. Ven-
dor-provided drivers might behave differently but are still likely to block on
write operations.
Write operations that complete quickly might have no noticeable or significant
effect on performance. Writing large blocks of data, especially at slow bit rates,
or writes that experience long delays due to flow control can hang an applica-
tion for more time than desired.
To enable doing other things while a write operation is in progress, an applica-
tion can perform the write operation in a separate thread. If needed, the appli-
cation can assign a routine to be called after the data has transmitted.
To perform write operations in a separate thread, define a delegate for the rou-
tine that writes to the port. The example delegate below includes a parameter
that holds a string to write to the port.
Free download pdf