private async Task OpenInternalAsync()

in iothub/device/src/Transport/Mqtt/MqttTransportHandler.cs [978:1046]


        private async Task OpenInternalAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (IsProxyConfigured())
            {
                // No need to do a DNS lookup since we have the proxy address already
#if NET451
                _serverAddresses = new IPAddress[0];
#else
                _serverAddresses = Array.Empty<IPAddress>();
#endif
            }
            else
            {
#if NET451
                _serverAddresses = Dns.GetHostEntry(_hostName).AddressList;
#elif NET6_0_OR_GREATER
                _serverAddresses = await Dns.GetHostAddressesAsync(_hostName, cancellationToken).ConfigureAwait(false);
#else
                _serverAddresses = await Dns.GetHostAddressesAsync(_hostName).ConfigureAwait(false);
#endif
            }

            if (TryStateTransition(TransportState.NotInitialized, TransportState.Opening))
            {
                try
                {
                    if (_channel != null
                        && _channel is IDisposable disposableChannel)
                    {
                        if (Logging.IsEnabled)
                            Logging.Info(this, $"_channel is disposable; disposing", nameof(OpenInternalAsync));

                        disposableChannel.Dispose();
                        _channel = null;
                    }
                    _channel = await _channelFactory(_serverAddresses, ProtocolGatewayPort).ConfigureAwait(true);
                }
                catch (Exception ex) when (!ex.IsFatal())
                {
                    OnError(ex);
                    throw;
                }

                ScheduleCleanup(async () =>
                {
                    _disconnectAwaitersCancellationSource?.Cancel();
                    if (_channel == null)
                    {
                        return;
                    }

                    if (_channel.Active)
                    {
                        await _channel.WriteAsync(DisconnectPacket.Instance).ConfigureAwait(true);
                    }

                    if (_channel.Open)
                    {
                        await _channel.CloseAsync().ConfigureAwait(true);
                    }
                });
            }

            await _connectCompletion.Task.ConfigureAwait(false);

            await SubscribeTwinResponsesAsync().ConfigureAwait(true);
        }