C# SocketAsyncEventArgs: why does it consume so much CPU?

280 Views Asked by At

SocketAsyncEventArgs is used to past the buffer, offset and length into the ReceiveAsync and SendAsync method of Socket.

I had done tests which revealed that,

  • If I don't dispose SocketAsyncEventArgs, it will cause memory leak.
  • Creating it, disposing it and calling its SetBuffer method all consume a huge amount of CPU.

It seems like a very bad and buggy implementation that SocketAsyncEventArgs, which simply acts as a wrapper to pass a buffer, its offset and length into the async methods of Socket, would consume so much CPU.

Does anyone know why? How do I use it with the async methods of Socket, then, without significantly slowing down my high-throughput server?

Following is the testing code. This Test method is called by 1000 threads. It is called 1000 times per second. But if I remove SocketAsyncEventArgs, it is called 8000 times per second. This seems to indicate that SocketAsyncEventArgs.SetBuffer consumes a huge amount of CPU.

    private static void Test(object obj)
    {
        TrueRandom random = new TrueRandom(500, 1300);
        SocketAsyncEventArgs args = new SocketAsyncEventArgs();

        while (true)
        {
            int iDesiredSize = random.GetRandomInteger() * 1000;
            byte[] buffer = null;

            try
            {
                buffer = ArrayPool<byte>.Shared.Rent(iDesiredSize);
                args.SetBuffer(buffer, 0, buffer.Length);
                ArrayPool<byte>.Shared.Return(buffer);
            }
            catch
            {
            }

            Thread.Sleep(100);
        }
    }
0

There are 0 best solutions below