Repository: dotnet/runtime
File: src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs (C#)

Code before:

            // In .NET 5 and earlier, the APM implementation allowed for synchronous exceptions from this to propagate
            // synchronously.  This call is made here rather than in the Core async method below to preserve that behavior.
            Task<IPAddress[]> addressesTask = Dns.GetHostAddressesAsync(endPoint.Host, parallelConnect ? AddressFamily.InterNetwork : endPoint.AddressFamily, cancellationToken);

            // Initialize the internal event args instance.  It needs to be initialized with `this` instance's buffer
            // so that it may be used as part of receives during a connect.
            // TODO https://github.com/dotnet/runtime/issues/30252#issuecomment-511231055: Try to avoid this extra level of SAEA.
            var internalArgs = new MultiConnectSocketAsyncEventArgs();
            internalArgs.CopyBufferFrom(this);

            // Delegate to the actual implementation.  The returned Task is unused and ignored, as the whole body is surrounded
            // by a try/catch.  Thus we ignore the result.  We avoid an "async void" method so as to skip the implicit SynchronizationContext
            // interactions async void methods entail.
#pragma warning disable CA2025
            if (parallelConnect)
            {
                var state = new ParallelMultiConnectSocketState(this);
                var internalArgsV6 = new MultiConnectSocketAsyncEventArgs();
                internalArgsV6.CopyBufferFrom(this);

                Task<IPAddress[]> addressesTask6 = Dns.GetHostAddressesAsync(endPoint.Host, AddressFamily.InterNetworkV6, cancellationToken);
                _ = Core(internalArgs, addressesTask, endPoint.Port, socketType, protocolType, state, cancellationToken);
                _ = Core(internalArgsV6, addressesTask6, endPoint.Port, socketType, protocolType, state, cancellationToken);
                return true;
            }
            else
            {
                _ = Core(internalArgs, addressesTask, endPoint.Port, socketType, protocolType, null, cancellationToken);
            }
#pragma warning restore

                // Determine whether the async operation already completed and stored the results into `this`.
                // If we reached this point and the operation hasn't yet stored the results, then it's considered
                // pending.  If by the time we get here it has stored the results, it's considered completed.
                // The callback won't invoke the Completed event if it gets there first.
                return internalArgs.ReachedCoordinationPointFirst();

            async Task Core(MultiConnectSocketAsyncEventArgs internalArgs, Task<IPAddress[]> addressesTask, int port, SocketType socketType, ProtocolType protocolType, ParallelMultiConnectSocketState? parallelState, CancellationToken cancellationToken)
            {
                Socket? tempSocketIPv4 = null, tempSocketIPv6 = null;
                Exception? caughtException = null;
                try
                {
                    // Try each address in turn.  We store the last error received, such that if we fail to connect to all addresses,
                    // we can use the last error to represent the entire operation.
                    SocketError lastError = SocketError.NoData;
                    foreach (IPAddress address in await addressesTask.ConfigureAwait(false))
                    {
                        Socket? attemptSocket = null;
                        if (_currentSocket != null)

Review comment (suggestion):
Will the OS resolver actually send an `AAAA`-only query here? (I remember testing it with packet captures but don't remember the outcome.)

Code after:
            bool parallelConnect = connectAlgorithm == ConnectAlgorithm.Parallel &&
                                            _currentSocket == null &&
                                            endPoint.AddressFamily == AddressFamily.Unspecified &&
                                            Socket.OSSupportsIPv6 && Socket.OSSupportsIPv4;

            // In .NET 5 and earlier, the APM implementation allowed for synchronous exceptions from this to propagate
            // synchronously.  This call is made here rather than in the Core async method below to preserve that behavior.
            Task<IPAddress[]> addressesTask = Dns.GetHostAddressesAsync(endPoint.Host, parallelConnect ? AddressFamily.InterNetwork : endPoint.AddressFamily, cancellationToken);

            // Initialize the internal event args instance.  It needs to be initialized with `this` instance's buffer
            // so that it may be used as part of receives during a connect.
            // TODO https://github.com/dotnet/runtime/issues/30252#issuecomment-511231055: Try to avoid this extra level of SAEA.
            var internalArgs = new MultiConnectSocketAsyncEventArgs();
            internalArgs.CopyBufferFrom(this);

            // Delegate to the actual implementation.  The returned Task is unused and ignored, as the whole body is surrounded
            // by a try/catch.  Thus we ignore the result.  We avoid an "async void" method so as to skip the implicit SynchronizationContext
            // interactions async void methods entail.
#pragma warning disable CA2025
            if (parallelConnect)
            {
                var state = new ParallelMultiConnectSocketState(this);
                var internalArgsV6 = new MultiConnectSocketAsyncEventArgs();
                internalArgsV6.CopyBufferFrom(this);

                Task<IPAddress[]> addressesTask6 = Dns.GetHostAddressesAsync(endPoint.Host, AddressFamily.InterNetworkV6, cancellationToken);
                _ = Core(internalArgs, addressesTask, endPoint.Port, socketType, protocolType, state, cancellationToken);
                _ = Core(internalArgsV6, addressesTask6, endPoint.Port, socketType, protocolType, state, cancellationToken);
                return true;
            }

            _ = Core(internalArgs, addressesTask, endPoint.Port, socketType, protocolType, null, cancellationToken);
#pragma warning restore

            // Determine whether the async operation already completed and stored the results into `this`.
            // If we reached this point and the operation hasn't yet stored the results, then it's considered
            // pending.  If by the time we get here it has stored the results, it's considered completed.
            // The callback won't invoke the Completed event if it gets there first.
            return internalArgs.ReachedCoordinationPointFirst();

            async Task Core(MultiConnectSocketAsyncEventArgs internalArgs, Task<IPAddress[]> addressesTask, int port, SocketType socketType, ProtocolType protocolType, ParallelMultiConnectSocketState? parallelState, CancellationToken cancellationToken)
            {
                Socket? tempSocketIPv4 = null, tempSocketIPv6 = null;
                Exception? caughtException = null;
                try
                {
                    // Try each address in turn.  We store the last error received, such that if we fail to connect to all addresses,
                    // we can use the last error to represent the entire operation.
                    SocketError lastError = SocketError.NoData;
                    foreach (IPAddress address in await addressesTask.ConfigureAwait(false))
                    {