I'm building an IRC client, and want an IRC independant networking class that just sends and receives lines between the client and server. Sending lines is OK, but I'm at a loss for a good way of implementing a listener thread. All the methods I've tried work, but have flaws that I can't get around.
My first method was to create a StreamReader
called _reader
using TcpClient.GetStream()
as a base, and just doing a _reader.ReadLine()
. This has the advantage that the background listener thread automatically stops until a line is received. The problem is that when I disconnect and stop the listener thread (or the application just exits), I'm not sure how good it is for garbage collection etc that the thread with the waiting ReadLine()
just gets killed. Could the thread get orphaned and somehow stay in the background stealing resources?
My second method was to create a NetworkStream
called _reader
based on the same TcpClient.GetStream()
, and create a loop that checks _reader.DataAvailable
and continue
the while loop if it's false, and otherwise push the bytes into a StringBuilder that is instantly checked for \r\n
and extracts any whole lines. This gives the same effect as the ReadLine on data retrieval, but I don't like the constant _reader.DataAvailable
looping. On my Core i5 CPU, it doesn't take any CPU but on my much more powerful i9 laptop it steals a virtual CPU constantly. Thread.Sleep(1)
"solves" this, but seems like a dirty fix, and numerous articles around the internet classify this as a code smell.
So what would be the proper solution?