Managing Ports and Transfers in .NET
private void AccessForm(string textToDisplay)
{
txtUserDisplay.AppendText(textToDisplay);
}
In the DataReceived routine, call AccessFormMarshal to pass data to display in
the form’s textbox:
Dim receivedData As String = myComPort.ReadExisting()
MyMainForm.AccessFormMarshal(receivedData)
string receivedData = myComPort.ReadExisting();
MyMainForm.AccessFormMarshal(receivedData);
8
$
Many applications collect a quantity of received data before taking action. For
example, a remote computer might send a large file for the receiving computer
to store, execute, or use in another way. A transmitting computer might also
send large quantities of data in multiple files or other blocks of data. In either
case, the application may need to provide a location to store data in sequence
from multiple read operations.
The ReadBufferSize property sets the size of the receive buffer with a minimum
size of 4096 bytes. If you expect a port to collect more than 4096 bytes of
received data before the application can read the data, increase the size of the
buffer. An application that knows how many bytes to expect can let the data
collect in the SerialPort buffer and use the BytesReceived property to find out
when all of the data has arrived.
Sometimes an application doesn’t know how much data will arrive, or the appli-
cation might need to examine the data as it comes in. The StringBuilder and
List(Of T) classes provide mechanisms for collecting and managing received
data.
! $
&
The StringBuilder class can collect received strings in a buffer that grows as
needed when the application appends new strings. For example, if receiving a
text file, an application can store the file as a single StringBuilder object. The
class is in the System.Text namespace.