Does async/await affects tcp server performance?

后端 未结 2 1563
我在风中等你
我在风中等你 2020-12-17 02:29

I am creating a Tcp server in C# 5.0 and I am using the await keyword when calling tcpListener.AcceptTcpClientAsync and networkStream.ReadAsync

相关标签:
2条回答
  • 2020-12-17 03:08

    I have also issues with an async and these are my findings: https://stackoverflow.com/a/22222578/307976

    Also, I have an asynchronous TCP server/client using async example here that scales well.

    0 讨论(0)
  • 2020-12-17 03:13

    Try the following implementation of ReceiveInt32Async and ReceiveDataAsync for receiving your length-prefixed messages directly, instead of using tcpClient.GetStream and networkStream.ReadAsync:

    public static class SocketsExt
    {
        static public async Task<Int32> ReceiveInt32Async(
            this TcpClient tcpClient)
        {
            var data = new byte[sizeof(Int32)];
            await tcpClient.ReceiveDataAsync(data).ConfigureAwait(false);
            return BitConverter.ToInt32(data, 0);
        }
    
        static public Task ReceiveDataAsync(
            this TcpClient tcpClient,
            byte[] buffer)
        {
            return Task.Factory.FromAsync(
                (asyncCallback, state) =>
                    tcpClient.Client.BeginReceive(buffer, 0, buffer.Length, 
                        SocketFlags.None, asyncCallback, state),
                (asyncResult) =>
                    tcpClient.Client.EndReceive(asyncResult), 
                null);
        }
    }
    

    See if this gives any improvements. On a side note, I also suggest making ReceiveDataFromClientAsync an async Task method and storing the Task it returns inside AsyncTcpClientConnection (for status and error tracking).

    0 讨论(0)
提交回复
热议问题