
Rentrancy issue with the Winsock control
Sure hope someone can help me on this. I have a VB6 (SP5) application that
uses the Microsoft Winsock control. This control connects to another
application and responds to that application's requests for information.
The problem is that while I am processing one piece of data, another piece
can arrive and this causes reentrancy. I have confirmed that there really
is an issue with reentrancy using a global variable to prove that the
control will fire the DataArrival event regardless of whether it is already
executing the code in that event. My solution was as follows:
'I have two module level variables: mstrBuffer and mblnHandlingMessage
Private Sub sckMessage_DataArrival(ByVal bytesTotal as Long)
'get data from the client
Dim strInboundData as String
sckMessage.GetData strInboundData
'combine the current message with the buffer
mstrBuffer = mstrBuffer & strInboundData
If Not mblnHandlingMessage Then
'Set the module level variable saying that we are processing
mblnHandlingMessage = True
'Get the endpoint for the first message
Dim lngPos as Long
lngPos = InStr(1, mstrBuffer, vbCrLf, vbTextCompare)
Do Until lngPos < 1
Dim strMessage as String
'grab the first message from the buffer and stuff it into a local
variable for processing
strMessage = Left$(mstrBuffer, lngPos - 1)
'Adjust the buffer so it no longer includes the data we just pulled
out.
mstrBuffer = Right$(mstrBuffer, Len(mstrBuffer) - (lngPos + 1))
'now we process the message we just got
mobjMessageParser.ParseMesssage strMessage
'Finally, check to see if there is another message to process
lngPos = InStr(1, mstrBuffer, vbCrLf, vbTextCompare)
Loop
'now that we are done, set the handling flag to false
mblnHandlingMessage = False
End If
End Sub
Unfortunately, I am told the above method may not guarantee that we do not
encounter problems due to reentrancy. There may be a very small window in
the following line of code:
mstrBuffer = Right$(mstrBuffer, Len(mstrBuffer) - (lngPos + 1))
I am told that it is possible that this routine could get re-entered
inbetween when the length of the buffer is determined and when the new
buffer value is assigned. If this is the case, the above line of code could
truncate one of our messages and cause some real problems.
What I am looking for is an answer on how to prevent the reentrancy in the
first place, or how to work around it if there is no way to prevent it.
This has to be resolvable without having to resort to C++.
TIA
Mike Riley