Using TCPClient's NetworkStream and protobuf-net I send and receive protobuf messages via TCP. Receiving is done with the following method that runs in an own thread:
private void HandleClientComm()
{
using (NetworkStream stream = m_Stream)
{
object o;
while (true)
{
if (stream.CanRead && stream.DataAvailable)
{
o = null;
if (Serializer.NonGeneric.TryDeserializeWithLengthPrefix(stream, PrefixStyle.Base128, Utilities.CommunicationHelper.resolver, out o))
{
if (o != null)
{
//Do something with the incoming protobuf object
}
}
Thread.Sleep(1);
}
}
}
}
This works fine, but I have a problem with the garbage collection. It seems like old protobuf objects are still kept in the memory. Large message lead to System.OutOfMemoryExceptions after a while.
Explicitly calling GC.Collect()
before sleeping fixes this problem. But it obviously slows down everything. How do I handle this properly?