title: Fastest possible UDP listener socket in .NET
body: <p>Hello guys I was wondering what would be the fastest possible reading mechanism for UDP packets.</p>
  
  <p>I was thinking about using socket async recieve, which should be the fastest way to receive data. Then having a processing loop in a different thread. </p>
  
  <p>Is this really the fastest possible way to do it?</p>
  
  <pre><code>static Socket udpListener;
  static byte[] buffer = new byte[5000];
  static ConcurrentQueue&lt;byte[]&gt; recievedPackets = new ConcurrentQueue&lt;byte[]&gt;();
  
  static void Main(string[] args)
  {
      udpListener = new Socket(SocketType.Dgram, ProtocolType.Udp);
      udpListener.Bind(new IPEndPoint(IPAddress.Any, 50000));
  
      StartRecievingChain();
  
      // Processing loop
      Task.Factory.StartNew(() =&gt;
      {
          int counter = 0;
          while (true)
          {
              if (recievedPackets.Count == 0)
                  Thread.Sleep(50);
  
              byte[] packet;
  
              if (recievedPackets.TryDequeue(out packet))
              {
                  counter++;
                  Console.WriteLine("Recieved {0} bytes", packet.Length);
              }
          }
      });
  
      Console.ReadKey();
  }
  
  static void StartRecievingChain()
  {
      SocketAsyncEventArgs recieveArgs = new SocketAsyncEventArgs();
      recieveArgs.SetBuffer(buffer, 0, buffer.Length);
      recieveArgs.Completed += ProcessRecievedPacket;
  
      if (!udpListener.ReceiveAsync(recieveArgs))
          ProcessRecievedPacket(null, recieveArgs);
  }
  
  static void ProcessRecievedPacket(object sender, SocketAsyncEventArgs e)
  {
      try
      {
          if (e.BytesTransferred &gt; 0 &amp;&amp; e.SocketError == SocketError.Success)
          {
              StartRecievingChain();
  
              byte[] data = new byte[e.BytesTransferred];
              Array.Copy(e.Buffer, data, e.BytesTransferred);
              recievedPackets.Enqueue(data);
          }
      }
      finally
      {
          e.Completed -= ProcessRecievedPacket;
          e.Dispose();
      }
  }
  </code></pre>