async Task ProcessPackets() { var buffer = new byte[MaxUdpSize]; var arraySegment = new ArraySegment <byte>(buffer); byte[] payload = new byte[MaxUdpSize]; EndPoint any = Any; while (true) { int read = _socket.ReceiveFrom(buffer, ref any); //var result = await _socket.ReceiveFromAsync(arraySegment, SocketFlags.None, any); // int read = result.ReceivedBytes; int payloadLength = 0; try { payloadLength = await _packetEncryption.Decrypt(buffer, read, payload); } catch (Exception exception) { Console.Error.WriteLine($"Failed to decrypted packet with exception {exception}"); continue; } HandlePacket(payload, payloadLength, (IPEndPoint)any); } }
async Task ProcessPackets() { byte[] buffer = new byte[MaxUdpSize]; byte[] payload = new byte[MaxUdpSize]; var segment = new ArraySegment <byte>(buffer); EndPoint any = Any; var resetEvent = new ManualResetEvent(false); var socketArgs = new SocketAsyncEventArgs(); socketArgs.SetBuffer(buffer); socketArgs.RemoteEndPoint = any; socketArgs.SocketFlags = SocketFlags.None; socketArgs.Completed += (sender, args) => { resetEvent.Set(); }; while (true) { if (_socket.ReceiveFromAsync(socketArgs)) { //didn't complete yet, need to wait for it await Task.Run(() => resetEvent.WaitOne()); resetEvent.Reset(); } try { int payloadLength = await _packetEncryption.Decrypt(buffer, socketArgs.BytesTransferred, payload); if (payloadLength != 0) { HandlePacket(payload, payloadLength, (IPEndPoint)socketArgs.RemoteEndPoint); } } catch (Exception exception) { Console.WriteLine($"Exception occured process ropu packet {exception.ToString()}"); } } }