Click here to Skip to main content
15,888,157 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a problem with the serial port:

My code:

VB
Dim readData() As Byte
Dim port As New SerialPort("COM1", 38400, Parity.None, 8)
port.StopBits = StopBits.One
port.Handshake = Handshake.None
port.ReadTimeout = 1000
port.Open()

port.Read(readData, 0, 8)

If readData.Length > 0 Then
   For Each b As Byte In readData
      Me.TextBox1.Text &= b.ToString("X2")
   Next
End If

port.Close()


trying to read the port immediately after it was opened gives me the following exception:

System.IO.IOException
The I/O operation has been aborted because of either a thread exit or an application request


But if I put a Thread Sleep between the Open and the Read lines, the problem goes away:

VB
port.Open()
System.Threading.Thread.Sleep(20)
port.Read(readData, 0, 8)


Somebody knows why this behavior?
Is it correct to use a Thread Sleep or is there a better solution?
Posted
Updated 6-Mar-19 20:30pm

Hmmm... I'm not seeing this problem. Doing some Googling, it seems you're not the only one running into this. It seems the SerialPort class might have a little bug in it.

What's weird is that if you compile the app Release and run it (NOT under the debugger!) it might work fine without the Sleep. Try it...

There's no harm in leaving it in there though.
 
Share this answer
 
Comments
cass3000 12-Mar-12 10:54am    
Thanks for your answer Dave.
Thanks for your answer Dave. I have tried to investigate this issue but I haven't had much luck, especially as the behavior of the port is not constant as far as I could try.

The problem that I posted was greatly reduced after restarting my PC, it seems it was something related to memory (I do not know really).

I completely avoid this error with the following extension method, I don't know if it's the best option, but I hope that helps.

VB
<extension()>
Public Sub OpenPort(ByVal port As SerialPort, Optional ByVal millisecondsSleep As Integer = 20)
   port.Open()
   System.Threading.Thread.Sleep(millisecondsSleep)
End Sub
 
Share this answer
 
Comments
Softvirtue 19-Sep-14 7:34am    
I Tried all these methods but still facing the same problem. Some Time it reads weight but most of the time programe just crash .

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900