public async Task SendPacketAsync(MqttBasePacket packet, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); using (await _syncRoot.WaitAsync(cancellationToken).ConfigureAwait(false)) { // Check for cancellation here again because "WaitAsync" might take some time. cancellationToken.ThrowIfCancellationRequested(); try { var packetData = PacketFormatterAdapter.Encode(packet); await _channel.WriteAsync(packetData.Array, packetData.Offset, packetData.Count, cancellationToken).ConfigureAwait(false); Interlocked.Add(ref _bytesReceived, packetData.Count); _logger.Verbose("TX ({0} bytes) >>> {1}", packetData.Count, packet); } catch (Exception exception) { if (IsWrappedException(exception)) { throw; } WrapAndThrowException(exception); } finally { PacketFormatterAdapter.FreeBuffer(); } } }
public async Task SendPacketAsync(MqttBasePacket packet, TimeSpan timeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); try { await _writerSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); } catch (ObjectDisposedException) { throw new OperationCanceledException(); } try { var packetData = PacketFormatterAdapter.Encode(packet); if (timeout == TimeSpan.Zero) { await _channel.WriteAsync(packetData.Array, packetData.Offset, packetData.Count, cancellationToken).ConfigureAwait(false); } else { await MqttTaskTimeout.WaitAsync( t => _channel.WriteAsync(packetData.Array, packetData.Offset, packetData.Count, t), timeout, cancellationToken).ConfigureAwait(false); } Interlocked.Add(ref _bytesReceived, packetData.Count); _logger.Verbose("TX ({0} bytes) >>> {1}", packetData.Count, packet); } catch (Exception exception) { if (IsWrappedException(exception)) { throw; } WrapException(exception); } finally { PacketFormatterAdapter.FreeBuffer(); try { _writerSemaphore.Release(); } catch (ObjectDisposedException) { throw new OperationCanceledException(); } } }