现在手上有一些历史的VB项目,是工控方面PLC控制的. 代码用了很多DoEvent 和时间等待. DoEvent的最大问题的不知道流程跳到哪里去了.
MSComm1.InBufferCount = 0 MSComm1.Output = nSendTemp DoEvents Start = timeGetTime Do While timeGetTime - Start < 500 '在毫秒内连续读PLC '16是返回位的长度,要等它返回完之后,才能继续下一步 If MSComm1.InBufferCount >= 16 Then Dim readTemp() As Byte readTemp = MSComm1.Input Dim nTemp(20) As Long If DispatchPlcData_Wr(readTemp, nTemp, 2) = False Then '读PLC错 nData(0) = 0 nData(1) = 0 GoTo EndFunc Else nData(0) = nTemp(0) nData(1) = nTemp(1) GetAddressData = True Exit Function End If End If DoEvents Loop
所以,不得以要用C#重新改造,重新捡起多线程.之前写WinForm比较少,重新学习一遍多线程.
1. IO密集型的,尽量不要用多线程,而是用异步方法.因为IO比CPU慢太多了.CPU只需要偶尔发个指令过去,然后在异步方法完成时处理一下就好了.