Мне нужно подключиться к электронной шкале AND GF 3000 с использованием RS232.Я проверил соединение, используя HyperT и собственную программу AND, и оно работает.Сейчас я создаю VB-приложение для чтения и пока оно действительно работает.Однако в некоторых частях он довольно глючный, поэтому я хочу оптимизировать его.
Моя предыдущая команда чтения использует:
Private Sub mscport_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles mscport.DataReceived
Dim tmpBuf As String
tmpBuf = mscport.ReadLine
End Sub
, что не является полной версией того, что я использую, но в остальномработает.Однако выход и повторное подключение (я использую элементы управления Windows Form) обнаруживает, что «операция ввода-вывода была прервана из-за исключения выхода из потока или запроса приложения».Оглядываясь в сети, я нашел причину от Дика Гриера: http://www.pcreview.co.uk/forums/serial-port-error-o-operation-has-been-abortedbecause-either-thread-exit-application-request-t2781073.html:
What this means, almost certainly, is that the SerialPort object attempted
to complete the call to ReadLine after the port has been closed. This can
happen because of the lack of synchronization between UI events which may
cause the port to close, and the background thread in the SerialPort object
that is performing the actual ReadFile operation (this executes as a result
of ReadLine in your delegate).
The problem with ReadLine, and the reason that I DO NOT use it, is that it
blocks until the the line terminating condition occurs -- this may be well
AFTER you have closed the port. Thus the exception.
I prefer simply buffering my own data in a Static or class-level variable
(all ReadExisting and append new data to the buffer) , and testing that
buffer for the vbCrLf terminating characters. If the vbCrLf is found (InStr
or Substring, your choice), then call a delegate to process and display the
data in the buffer. Remember to clear this buffer AFTER you have processed
and displayed its content. If you do this, the exception should be
resolved.
Dick
Ранее мое приложение использовало ReadExisting вместо ReadLine для последовательного соединения.Позже, при использовании USB-последовательного кабеля, ReadExisting не работал, поэтому я использовал ReadLine вместо этого.Я хочу использовать USB-кабель, поэтому мне нужно найти способ заменить ReadLine.Теперь я не очень хорош в последовательных портах, но мне удалось сделать почти рабочий код, заменив ReadLine, используя ReadChar, который находится здесь:
Private Sub mscport_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles mscport.DataReceived
Dim tmpbuf As String
Dim bytebuffer(17) As Byte
Dim count As Integer = 17
Try
While count > 0
bytebuffer(17 - count) = mscport.ReadChar
'If bytebuffer(17 - count) = vbCrLf Then
'End If
'tmpBuf = tmpBuf & mscport.ReadExisting
count = count - 1
End While
Catch ex As InvalidOperationException
MessageBox.Show(ex.Message)
Catch ex As UnauthorizedAccessException
MessageBox.Show(ex.Message)
Catch ex As System.IO.IOException
MessageBox.Show(ex.Message)
End Try
tmpbuf = tmpbuf & System.Text.Encoding.ASCII.GetString(bytebuffer, 0, 17)
'tmpBuf = bytebuffer.ToString()
ReceiveData(tmpbuf)
End Sub
Проблема сновый код:
Исключение ввода-вывода все еще существует.Иногда срабатывает при открытии приложения.Даже со всеми этими исключениями он все еще не уловил.
Данные иногда получают все перемешанные. Например, ST 0009.80 г отображается как .80 gST 0009. Данные заканчиваютсяс CrLf, так что я все еще думаю о том, как переставить его перед отображением.
Я знаю, что есть лучший способ сделать это, я просто не мог придумать один, или, может быть,Я не ищу достаточно.