异步/等待 是否会影响 TCP 服务器性能?

6
我正在使用C# 5.0创建Tcp服务器,并在调用tcpListener.AcceptTcpClientAsyncnetworkStream.ReadAsync时使用await关键字。
但是,当我通过Process Explorer检查服务器的CPU使用率时,得到以下结果:
Tcp同步版本: 10%的CPU使用率 Tcp异步版本: 30%的CPU使用率其中一半是内核使用率。
此外,我通过在网络流的while循环中添加计数器来测量接收数据的次数,异步版本循环了120,000次,而同步版本则循环了2,500,000次。
就每秒收到的消息数量而言,异步版本在从3个不同的客户端接收消息时比同步版本慢15%。 为什么异步版本使用的CPU比同步版本多得多? 这是因为async/await关键字吗? 异步Tcp服务器比其同步对应物慢是正常的吗? 编辑:这里是异步Tcp服务器代码示例
public class AsyncTcpListener : ITcpListener
{ 
    private readonly ServerEndpoint _serverEndPoint;  // Custom class to store IpAddress and Port

    public bool IsRunning { get; private set; }

    private readonly List<AsyncTcpClientConnection> _tcpClientConnections = new List<AsyncTcpClientConnection>(); 

    private TcpListener _tcpListener;

    public AsyncTcpMetricListener()
    {
        _serverEndPoint = GetServerEndpoint();  
    }

    public async void Start()
    {
        IsRunning = true;

        RunTcpListener();
    }

    private void MessageArrived(byte[] buffer)
    { 
        // Deserialize
    }

    private void RunTcpListener(){
       _tcpListener = null;
        try
        {
            _tcpListener = new TcpListener(_serverEndPoint.IpAddress, _serverEndPoint.Port);
            _tcpListener.Start();
            while (true)
            {
                var tcpClient = await _tcpListener.AcceptTcpClientAsync().ConfigureAwait(false);
                var asyncTcpClientConnection = new AsyncTcpClientConnection(tcpClient,  MessageArrived);
                _tcpClientConnections.Add(asyncTcpClientConnection);
            }
        } 
        finally
        {
            if (_tcpListener != null)
                _tcpListener.Stop();

            IsRunning = false;
        }
    }

    public void Stop()
    {
        IsRunning = false; 
        _tcpListener.Stop();
        _tcpClientConnections.ForEach(c => c.Close());
    }
}

对于每个新客户,我们都会创建一个新的AsyncTcpConnection。

public class AsyncTcpClientConnection
{ 
    private readonly Action<byte[]> _messageArrived;
    private readonly TcpClient _tcpClient; 

    public AsyncTcpClientConnection(TcpClient tcpClient, Action<byte[]> messageArrived)
    {
        _messageArrived = messageArrived;
        _tcpClient = tcpClient; 
        ReceiveDataFromClientAsync(_tcpClient); 
    }

    private async void ReceiveDataFromClientAsync(TcpClient tcpClient)
    {
        var readBuffer = new byte[2048];
        // PacketProtocol class comes from http://blog.stephencleary.com/2009/04/sample-code-length-prefix-message.html
        var packetProtocol = new PacketProtocol(2048);  
        packetProtocol.MessageArrived += _messageArrived;

        try
        {
            using (tcpClient)
            using (var networkStream = tcpClient.GetStream())
            {
                int readSize;
                while ((readSize = await networkStream.ReadAsync(readBuffer, 0, readBuffer.Length).ConfigureAwait(false)) != 0)
                {
                    packetProtocol.DataReceived(readBuffer, readSize); 
                }
            }
        } 
        catch (Exception ex)
        {
            // log
        } 
    } 

    public void Close()
    {
        _tcpClient.Close();
    }
}

编辑2:同步服务器

 public class TcpListener : ITcpListener
{  
    private readonly ObserverEndpoint _serverEndPoint; 
    private readonly List<TcpClientConnection> _tcpClientConnections = new List<TcpClientConnection>();

    private Thread _listeningThread;
    private TcpListener _tcpListener;
    public bool IsRunning { get; private set; }

    public TcpMetricListener()
    {
        _serverEndPoint = GetServerEndpoint();   

    }


    public void Start()
    {
        IsRunning = true;
        _listeningThread = BackgroundThread.Start(RunTcpListener);  
    }

    public void Stop()
    {
        IsRunning = false;

        _tcpListener.Stop();
        _listeningThread.Join();
        _tcpClientConnections.ForEach(c => c.Close());
    }

    private void MessageArrived(byte[] buffer)
    {
        // Deserialize
    }

    private void RunTcpListener()
    {
        _tcpListener = null;
        try
        {
            _tcpListener = new TcpListener(_serverEndPoint.IpAddress, _serverEndPoint.Port);
            _tcpListener.Start();
            while (true)
            {
                var tcpClient = _tcpListener.AcceptTcpClient();
                _tcpClientConnections.Add(new TcpClientConnection(tcpClient, MessageArrived));
            }
        } 
        finally
        {
            if (_tcpListener != null)
                _tcpListener.Stop();

            IsRunning = false;
        }
    }
}

连接的问题
public class TcpClientConnection
{ 
    private readonly Action<byte[]> _messageArrived;
    private readonly TcpClient _tcpClient;
    private readonly Task _task; 
    public TcpClientConnection(TcpClient tcpClient,   Action<byte[]> messageArrived)
    {
        _messageArrived = messageArrived;
        _tcpClient = tcpClient; 
        _task = Task.Factory.StartNew(() => ReceiveDataFromClient(_tcpClient), TaskCreationOptions.LongRunning);

    }

    private void ReceiveDataFromClient(TcpClient tcpClient)
    {
        var readBuffer = new byte[2048];
        var packetProtocol = new PacketProtocol(2048);
        packetProtocol.MessageArrived += _messageArrived;


            using (tcpClient)
            using (var networkStream = tcpClient.GetStream())
            {
                int readSize;
                while ((readSize = networkStream.Read(readBuffer, 0, readBuffer.Length)) != 0)
                {
                    packetProtocol.DataReceived(readBuffer, readSize); 
                }
            } 
    }


    public void Close()
    {
        _tcpClient.Close();
        _task.Wait();
    }
}

AsyncTcpClientConnection 中,您没有等待调用 ReceiveDataFromClientAsync。虽然与性能无关,但仍然是一个错误。 - Sergei Rogovtcev
1
我不能等待ReceiveDataFromClientAsync,因为程序会永远等待,而且无法监听另一个TCP客户端。 - alexandrekow
看看这个是否有帮助 http://msdn.microsoft.com/zh-cn/magazine/dn605876.aspx - Paulo Morgado
2个回答

0
尝试使用以下实现 ReceiveInt32AsyncReceiveDataAsync 直接接收您的长度前缀消息,而不是使用 tcpClient.GetStreamnetworkStream.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);
    }
}

看看这是否有任何改进。另外,我建议将ReceiveDataFromClientAsync方法改为async Task方法,并将其返回的Task存储在AsyncTcpClientConnection中(用于状态和错误跟踪)。


我尝试了你的实现,发现有两个问题:1)速度慢得多(每秒只能处理4k条消息,而不是220k条消息)。2)它没有考虑到我们在TCP中可能会接收到不完整的数据包。但是,这是非常优雅的代码。 - alexandrekow
@alexandrekow,1)我认为值得一试:),2)我认为这就是消息长度前缀的作用。理论上,像这样的异步接收操作直到所有请求的数据都被接收才算完成;即对于Int32,只有在接收到4个字节时才算完成,对于buff[] - buff.Length字节。 - noseratio - open to work
@alexandrekow,还有一步是尝试使用增加的Socket.ReceiveBufferSize来实现。 - noseratio - open to work

0

感谢分享您的见解。您的实现很好。我喜欢您处理服务器干净关闭的方式。我使用了您的服务器实现代码来重构我的监听器。然而,性能仍然相同,CPU峰值也相同。 - alexandrekow
你检查过那些 CPU 峰值不是由于清理垃圾所引起的吗?打开性能收集器,为您的服务器应用程序实例添加“% of time in GC”计数器,并检查这些峰值是否与您提到的峰值相符。我有一种感觉,异步代码对 GC 会造成困扰。 - vtortola
我的算法中垃圾回收占用不到1%的时间。 - alexandrekow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接