public async Task <ProcessRequestResult> ProcessRequestAsync(RTURequest request, int timeout, int retries, int?delayBetweenMessages, CancellationToken cancellationToken)
        {
            int           attempts        = 0;
            Memory <byte> responseMessage = new Memory <byte>();
            int           bytesSent       = 0;
            int           packetsSent     = 0;
            int           bytesReceived   = 0;
            int           packetsReceived = 0;
            DateTime      startTimestamp  = DateTime.UtcNow;

            while (attempts <= retries)
            {
                try
                {
                    await _requestSemaphore.WaitAsync(cancellationToken);

                    if (attempts > 0)
                    {
                        await destroyAndInitializeClient(request.UnitID, timeout, cancellationToken);
                    }

                    // Build the Request into a Message we can Send
                    ReadOnlyMemory <byte> requestMessage = request.BuildMessage();

                    TimeSpan timeSinceLastMessage = DateTime.UtcNow.Subtract(_lastMessageTimestamp);

                    if (delayBetweenMessages.HasValue && delayBetweenMessages.Value > 0 && timeSinceLastMessage.TotalMilliseconds < delayBetweenMessages.Value)
                    {
                        await Task.Delay(TimeSpan.FromMilliseconds(delayBetweenMessages.Value - timeSinceLastMessage.TotalMilliseconds), cancellationToken);
                    }

                    // Send the Message
                    SendMessageResult sendResult = await sendMessageAsync(request.UnitID, requestMessage, timeout, cancellationToken);

                    bytesSent   += sendResult.Bytes;
                    packetsSent += sendResult.Packets;

                    // Receive a Response
                    ReceiveMessageResult receiveResult = await receiveMessageAsync(request, request.UnitID, timeout, cancellationToken);

                    bytesReceived   += receiveResult.Bytes;
                    packetsReceived += receiveResult.Packets;
                    responseMessage  = receiveResult.Message;

                    break;
                }
                catch (Exception)
                {
                    if (attempts >= retries)
                    {
                        throw;
                    }
                }
                finally
                {
                    _requestSemaphore.Release();
                }

                // Increment the Attempts
                attempts++;
            }

            try
            {
                return(new ProcessRequestResult
                {
                    BytesSent = bytesSent,
                    PacketsSent = packetsSent,
                    BytesReceived = bytesReceived,
                    PacketsReceived = packetsReceived,
                    Duration = DateTime.UtcNow.Subtract(startTimestamp).TotalMilliseconds,
                    Response = RTUResponse.CreateNew(responseMessage, request),
                });
            }
            catch (RTUException e)
            {
                throw new ModbusException("Received an RTU Error Response from Modbus Device ID '" + request.UnitID + "' on '" + _remoteHost + ":" + _port + "'", e);
            }
        }
        private async Task <ReceiveMessageResult> receiveMessageAsync(RTURequest request, byte unitId, int timeout, CancellationToken cancellationToken)
        {
            ReceiveMessageResult result = new ReceiveMessageResult
            {
                Bytes   = 0,
                Packets = 0,
                Message = new Memory <byte>(),
            };

            try
            {
                List <byte> receivedData   = new List <byte>();
                DateTime    startTimestamp = DateTime.UtcNow;

                while (DateTime.UtcNow.Subtract(startTimestamp).TotalMilliseconds < timeout && receivedData.Count < RTUResponse.GetMessageLengthHint(request, receivedData) + 3)
                {
                    Memory <byte> buffer         = new byte[300];
                    TimeSpan      receiveTimeout = TimeSpan.FromMilliseconds(timeout).Subtract(DateTime.UtcNow.Subtract(startTimestamp));

                    if (receiveTimeout.TotalMilliseconds >= 50)
                    {
                        int receivedBytes = await _client.ReceiveAsync(buffer, receiveTimeout, cancellationToken);

                        if (receivedBytes > 0)
                        {
                            receivedData.AddRange(buffer.Slice(0, receivedBytes).ToArray());

                            result.Bytes   += receivedBytes;
                            result.Packets += 1;
                        }
                    }
                }

                if (receivedData.Count == 0)
                {
                    throw new ModbusException("Failed to Receive RTU Message from Modbus Device ID '" + unitId + "' on '" + RemoteHost + ":" + Port + "' - No Data was Received");
                }

                if (receivedData.Count < RTUResponse.GetMessageLengthHint(request, receivedData) + 3)
                {
                    throw new ModbusException("Failed to Receive RTU Message within the Timeout Period from Modbus Device ID '" + unitId + "' on '" + RemoteHost + ":" + Port + "'");
                }

                if (receivedData[0] != unitId)
                {
                    throw new ModbusException("Failed to Receive RTU Message from Modbus Device ID '" + unitId + "' on '" + RemoteHost + ":" + Port + "' - The Unit ID did not Match");
                }

                receivedData.RemoveRange(0, 1);

                receivedData.RemoveRange(receivedData.Count - 2, 2);

                result.Message = receivedData.ToArray();
            }
            catch (ObjectDisposedException)
            {
                throw new ModbusException("Failed to Receive RTU Message from Modbus Device ID '" + unitId + "' on '" + RemoteHost + ":" + Port + "' - The underlying Socket Connection has been Closed");
            }
            catch (TimeoutException)
            {
                throw new ModbusException("Failed to Receive RTU Message within the Timeout Period from Modbus Device ID '" + unitId + "' on '" + RemoteHost + ":" + Port + "'");
            }
            catch (System.Net.Sockets.SocketException e)
            {
                throw new ModbusException("Failed to Receive RTU Message from Modbus Device ID '" + unitId + "' on '" + RemoteHost + ":" + Port + "'", e);
            }

            return(result);
        }
        private async Task <ReceiveMessageResult> receiveMessageAsync(byte unitId, int timeout, CancellationToken cancellationToken)
        {
            ReceiveMessageResult result = new ReceiveMessageResult
            {
                Bytes   = 0,
                Packets = 0,
                Message = new Memory <byte>(),
            };

            try
            {
                List <byte> receivedData   = new List <byte>();
                DateTime    startTimestamp = DateTime.UtcNow;

                while (DateTime.UtcNow.Subtract(startTimestamp).TotalMilliseconds < timeout && receivedData.Count < MBAPHeaderLength)
                {
                    Memory <byte> buffer         = new byte[300];
                    TimeSpan      receiveTimeout = TimeSpan.FromMilliseconds(timeout).Subtract(DateTime.UtcNow.Subtract(startTimestamp));

                    if (receiveTimeout.TotalMilliseconds >= 50)
                    {
                        int receivedBytes = await _client.ReceiveAsync(buffer, receiveTimeout, cancellationToken);

                        if (receivedBytes > 0)
                        {
                            receivedData.AddRange(buffer.Slice(0, receivedBytes).ToArray());

                            result.Bytes   += receivedBytes;
                            result.Packets += 1;
                        }
                    }
                }

                if (receivedData.Count == 0)
                {
                    throw new ModbusException("Failed to Receive RTU Message from Modbus TCP Device '" + RemoteHost + ":" + Port + "' - No Data was Received");
                }

                if (receivedData.Count < MBAPHeaderLength)
                {
                    throw new ModbusException("Failed to Receive RTU Message within the Timeout Period from Modbus TCP Device '" + RemoteHost + ":" + Port + "'");
                }

                if (receivedData[2] != 0 || receivedData[3] != 0)
                {
                    throw new ModbusException("Failed to Receive RTU Message from Modbus TCP Device  '" + RemoteHost + ":" + Port + "' - The TCP Header was Invalid");
                }

                if (BitConverter.ToUInt16(receivedData.GetRange(0, 2).ToArray(), 0) != _requestId)
                {
                    throw new ModbusException("Failed to Receive RTU Message from Modbus TCP Device  '" + RemoteHost + ":" + Port + "' - The TCP Header Transaction ID did not Match");
                }

                if (receivedData[6] != unitId)
                {
                    throw new ModbusException("Failed to Receive RTU Message from Modbus TCP Device  '" + RemoteHost + ":" + Port + "' - The TCP Header Unit ID did not Match");
                }

                byte[] mbapHeader = receivedData.GetRange(0, MBAPHeaderLength).ToArray();

                int tcpMessageDataLength = BitConverter.ToUInt16(new byte[] { receivedData[5], receivedData[4] }) - 1;

                if (tcpMessageDataLength <= 0 || tcpMessageDataLength > byte.MaxValue)
                {
                    throw new ModbusException("Failed to Receive RTU Message from Modbus TCP Device  '" + RemoteHost + ":" + Port + "' - The TCP Message Length was Invalid");
                }

                receivedData.RemoveRange(0, MBAPHeaderLength);

                if (receivedData.Count < tcpMessageDataLength)
                {
                    startTimestamp = DateTime.UtcNow;

                    while (DateTime.UtcNow.Subtract(startTimestamp).TotalMilliseconds < timeout && receivedData.Count < tcpMessageDataLength)
                    {
                        Memory <byte> buffer         = new byte[300];
                        TimeSpan      receiveTimeout = TimeSpan.FromMilliseconds(timeout).Subtract(DateTime.UtcNow.Subtract(startTimestamp));

                        if (receiveTimeout.TotalMilliseconds >= 50)
                        {
                            int receivedBytes = await _client.ReceiveAsync(buffer, receiveTimeout, cancellationToken);

                            if (receivedBytes > 0)
                            {
                                receivedData.AddRange(buffer.Slice(0, receivedBytes).ToArray());
                            }

                            result.Bytes   += receivedBytes;
                            result.Packets += 1;
                        }
                    }
                }

                if (receivedData.Count == 0)
                {
                    throw new ModbusException("Failed to Receive RTU Message from Modbus TCP Device  '" + RemoteHost + ":" + Port + "' - No Data was Received after TCP Header");
                }

                if (receivedData.Count < tcpMessageDataLength)
                {
                    throw new ModbusException("Failed to Receive RTU Message within the Timeout Period from Modbus TCP Device  '" + RemoteHost + ":" + Port + "'");
                }

                result.Message = receivedData.ToArray();
            }
            catch (ObjectDisposedException)
            {
                throw new ModbusException("Failed to Receive RTU Message from Modbus TCP Device '" + RemoteHost + ":" + Port + "' - The underlying Socket Connection has been Closed");
            }
            catch (TimeoutException)
            {
                throw new ModbusException("Failed to Receive RTU Message within the Timeout Period from Modbus TCP Device  '" + RemoteHost + ":" + Port + "'");
            }
            catch (System.Net.Sockets.SocketException e)
            {
                throw new ModbusException("Failed to Receive RTU Message from Modbus TCP Device  '" + RemoteHost + ":" + Port + "'", e);
            }

            return(result);
        }