问题描述:

my application performes serial communication with a microcontroller.

Here is the event:

Public Event DataReceived As IO.Ports.SerialDataReceivedEventHandler

Handling the Event:

Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

MyReceivedSerialData = SerialPort1.ReadExisting

Me.Invoke(New EventHandler(AddressOf SerialThreadHandler))

End Sub

The SerialThreadHandler() processes the received data...

However the user has also the option to disconnect from the serial interface.

In this case this procedure is executed:

Public Sub MyDisconnectAndClose()

If frmUploadData.SerialPort1.IsOpen = True Then

Try

frmUploadData.SerialPort1.Close()

frmUploadData.Close()

frmUploadData.Dispose()

Catch ex As Exception

MessageBox.Show(ex.Message)

End Try

End If

End Sub

If there is data transmitted or received during the disconnect, the whole application will hang.

This is a known issue and I am not the first one who encounters this...

As a possible solution, there is the recommandation, to use BeginInvoke instead of Invoke.

Invoke = synchronus

BeginInvoke = asynchronus

When I use BeginInvoke

Me.BeginInvoke(New EventHandler(AddressOf SerialThreadHandler))

The disconnect does not cause a hangup any more, but due to the asynchronus communication the communication does stop at random points - this is definitely a side effect or issue of the asynchronous communication, because the application is extensively receiving and transmitting data...

Is there any other way, to create a workaround or solution for this problem?

相关阅读:
Top