繁体   English   中英

如何使用NetworkStream正确处理传入的protobuf消息?

[英]How to properly handle incoming protobuf message with a NetworkStream?

使用TCPClient的NetworkStream和protobuf-net,我通过TCP发送和接收protobuf消息。 接收是通过在自己的线程中运行的以下方法完成的:

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);
            }
        }
    }   
}

这工作正常,但是我对垃圾回收有问题。 似乎旧的protobuf对象仍保留在内存中。 一段时间后,大消息导致System.OutOfMemoryExceptions。

在睡眠之前显式调用GC.Collect()可解决此问题。 但这显然会减慢一切。 我该如何正确处理?

protobuf网本身是不会保留旧的邮件保持-事实上,如果有人这样做,在GC.Collect不会有帮助。

我首先看到的是,在DataAvailable上等待的热循环确实非常昂贵。 这可能会干扰GC 我可以看到的第二件事是,您可能可以睡眠之前o释放对象。 作为随机尝试,也许:

using (NetworkStream stream = m_Stream)
{
    object o;
    while (Serializer.NonGeneric.TryDeserializeWithLengthPrefix(
        stream, PrefixStyle.Base128,
        Utilities.CommunicationHelper.resolver, out o))
    {
        if (o != null)
        {
            //TODO: Do something with the incoming protobuf object

            // clear o, just to give GC the very best chance while we sleep
            o = null;
        }
        Thread.Sleep(1); // <=== not sure why you want to sleep here, btw
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM