I am trying to receive messages from Chrome using Google NativeMessaging
, my WinForms
application reads the messages sent from my extension in Chrome by calling the following function each 0.1s:
Public Function read_message() As String
'Read in first 4 bytes for length...
Dim stdin As Stream = Console.OpenStandardInput()
Dim bytelen(LENGTH_BYTE_COUNT - 1) As Byte
stdin.Read(bytelen, 0, LENGTH_BYTE_COUNT)
Dim msglen As Integer = BitConverter.ToInt32(bytelen, 0)
'Read the message
Dim msg As String = ""
For i As Integer = 0 To msglen - 1
msg &= ChrW(stdin.ReadByte())
Next i
stdin.Close()
stdin.Dispose()
Return msg
End Function
Everything works perfectly in the scenario I explained above, however, I wanted this function to run repeatedly in a different Thread.
So when I am creating new thread, that has similar timer with similar interval, the results become a mess, text messages from Chrome overlaps, some messages are simply missed, and some times return corrupt messages, and I can't understand why this works perfectly in UI thread, while gives strange results in a different one, even if I relax reading time interval, any clues?
P.S
As a side question, I am actually not sure that using a timer to read messages from stdin is best approach given that I have to use Winforms, is there any better way to detect when a message "arrives" into stdin stream?