我正在运行Windows服务,在COM4上每秒24小时检查硬件仪器大约15次。当仪器收到命令时,它会相应地做出响应,以>CRLF
结束其响应以指示往返完成。
以下代码给了我一些麻烦:
01 Public Async Function SendAsync() As Task(Of Response)
02 Dim oResponse As Response
03 Dim sData As String
04
05 Do
06 Me.Port.WriteLine(Me.Instruction)
07
08 sData = Await ReadResponseAsync()
09 oResponse = New Response(Me.Instruction, sData)
10 Loop While oResponse.Status = Response.States.SyntaxError
11
12 Return oResponse
13 End Function
14
15 Private Async Function ReadResponseAsync() As Task(Of String)
16 Dim iSize As Integer
17 Dim sData As String
18 Dim aData As Byte()
19
20 aData = New Byte(255) {}
21 sData = String.Empty
22
23 Do
24 iSize = Await Me.Port.BaseStream.ReadAsync(aData, 0, aData.Length)
25 sData &= Encoding.ASCII.GetString(aData, 0, iSize)
26 Loop While Not sData.EndsWith($">{vbCrLf}")
27
28 Return sData
29 End Function
我在第24行得到了一个罕见的IOException
:
System.IO.IOException:由于线程退出或应用程序请求,I / O操作已中止。
在过去的144小时内发生了两次,在大约3.8mm的挑战/响应周期中给出了1的比率。它与任何服务停止操作都不对应。
这是否意味着该周期的数据永远不会丢失给我?
如果我将ReadAsync()
调用包装在Try / Catch中,那么下一个循环是否会收到等待响应?
Do
Try
iSize = Await Me.Port.BaseStream.ReadAsync(aData, 0, aData.Length)
sData &= Encoding.ASCII.GetString(aData, 0, iSize)
Catch ex As IOException
Main.Logger.Warn("IOException was skipped. Data will be retrieved on next attempt.")
aData = New Byte(255) {}
sData = String.Empty
End Try
Loop While Not sData.EndsWith($">{vbCrLf}")
我想对此进行快速测试,但我无法在上下文中重现IOException
。