To prevent crashes, wait for all data to transmit before closing
the port. To prevent an endless wait, set the port??™s WriteTimeout property. On a
timeout, the port??™s BytesToWrite property is set to zero, and the port can close
without a crash.
If (Not (myComPort Is Nothing)) Then
??? The COM port exists.
If myComPort.IsOpen Then
' Wait for the transmit buffer to empty.
Do While (myComPort.BytesToWrite > 0)
Loop
??? The COM port is open; close it and dispose of its resourced.
myComPort.Dispose()
End If
End If
if (!(myComPort == null))
{
// The COM port exists.
if ( myComPort.IsOpen )
{
// Wait for the transmit buffer to empty.
while (myComPort.BytesToWrite > 0)
{
}
// The COM port is open; close it and dispose of its resources.
myComPort.Dispose();
}
}
Using .NET??™s SerialPort Class
163
An alternate way to close a port is with a Using block. On exiting the Using
block, the SerialPort object named in the Using statement is closed automatically
and its resources are disposed of:
Using myComPort As New SerialPort
myComPort.PortName = "COM6"
myComPort.BaudRate = 115200
myComPort.Open()
myComPort.WriteLine("hello")
End Using
using (SerialPort myComPort = new SerialPort())
{
myComPort.PortName = "COM6";
myComPort.BaudRate = 115200;
myComPort.Open();
myComPort.WriteLine("hello");
}
Closing a port can take up to a few seconds (or longer if waiting for the port to
finish transmitting), so applications and users should delay a bit between closing
a port and re-opening the same port.
Pages:
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200