BeginRead缓冲区大小(繁重的CPU负载)

时间:2012-05-09 20:03:11

标签: c# networking

我的async tcp客户端 - 服务器应用现在正在运行。

但我有一些CPU负载问题。如果我将网络缓冲区设置为8192它适用于小消息,但如果我传输超过1MB我的CPU负载真的很高..我可以通过将缓冲区设置为81920来修复它。

解决此问题的任何解决方案?我想将数据从几KB转移到几百MB。

有多个TCP连接,每个缓冲区大小不同,这是个好主意吗?还有其他解决方案吗?

我的代码也可能存在性能问题。

我的阅读代码:

private class ReadClientState
    {
        public TcpClient Client { get; set; }
        public byte[] Buffer { get; set; } // buffer size...???

        public byte[] inc_message { get; set; }
        public int inc_message_size  { get; set; }
    }

BeginRead回调:

private void ReadCallback(IAsyncResult ar)
    {
        ReadClientState state = (ReadClientState)ar.AsyncState;
        int cbRead = 0;
        try
        {
            cbRead = state.Client.GetStream().EndRead(ar);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            if (ex.InnerException is SocketException)
            {
                if (((SocketException)ex.InnerException).ErrorCode == 10054)
                {
                    ...
                }
            }
            return;
        }

// read 4 byte lenght header (new message incoming)
        if (state.inc_message_size == 0)
        {
            byte[] header = new byte[4];
            Buffer.BlockCopy(state.Buffer, 0, header, 0, 4);
            state.inc_message_size = BitConverter.ToInt32(header, 0);
        }

// copy buffer to message data array
        byte[] tmp = new byte[cbRead];
        Buffer.BlockCopy(state.Buffer, 0, tmp, 0, cbRead);
        state.inc_message = state.inc_message.Concat(tmp).ToArray();
        state.Buffer = new byte[bufferSize];


        Array.Clear(state.Buffer, 0, state.Buffer.Length);


// message is complete
        if (state.inc_message.Length >= state.inc_message_size)
        {
            if (state.inc_message.Length > state.inc_message_size)
            {
                Console.WriteLine("ERROR.. read more than expected");
            }
            else
            {
                Console.WriteLine("massage size: " + state.inc_message_size.ToString() + " total bytes read: " + state.inc_message.Length.ToString());

                Array.Clear(state.inc_message, 0, state.inc_message.Length);
                state.inc_message_size = 0;
            }
        }

        try
        {
            state.Client.GetStream().BeginRead(state.Buffer, 0, state.Buffer.Length, ReadCallback, state);
        }
        catch (Exception ex)
        {
            return;
        }
    }

0 个答案:

没有答案