A while ago i wrote some basic Http webserver in vb.net. I tried to avoid blocking IO, so basically i made one polling thread for all current connections.
While True
For Each oNetworkstream In lstNetworkstream
If oNetworkstream.DataAvailable Then
'Read from stream
End If
Next
End While
So whenever a connection had some new data, i could read it, otherwise immediately check the next connection.
Now i'm extending the webserver with https. Therefore, i used the .Net SslStream Class. I would like to apply the same principle (one polling thread to read all streams)
Since there is no .DataAvailable property, i tried width .Length > 0, but this gives a NotSupportedException (This stream does not support seek operations)
Dim oSslStream As New SslStream(oStream, False)
oSslStream.AuthenticateAsServer(moCertificateKeyPair)
MsgBox(oSslStream.Length)
So, how could i determine if a certain decrypted stream has data available without blocking the thread?
Avoiding blocking is a good idea when you have many connections. But polling is not the way to solve it.
Instead, you should use async IO. Let the system notify you when data is ready.
With C# 5 you should use
async/await
+ReadAsync
. In lower C# versions you should use Task-based IO (IOW still useReadAsync
is available). If it is not available, write your own version. If you can't do that, useBeginRead
.