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

Code before:
            _ = Core(internalArgs, addressesTask, endPoint.Port, socketType, protocolType, connectAlgorithm, 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, ConnectAlgorithm connectAlgorithm, 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;
                    IPAddress[] addresses = await addressesTask.ConfigureAwait(false);
                    IPAddress? address = null;
                    IPAddress? address2 = null;
                    AddressFamily currentAddressFamily = AddressFamily.InterNetwork;

                    int nextAddressIndex = 0;
                    int nextIPv6AddressIndex = GetNextAddressIndex(addresses, AddressFamily.InterNetworkV6, -1);
                    int nextUPv4AddressIndex = GetNextAddressIndex(addresses, AddressFamily.InterNetwork, -1);


                    // We can do parallel connect only if socket was not specified and when there is at least one address of each AF.
                    bool parallelConnect = connectAlgorithm == ConnectAlgorithm.Parallel && _currentSocket == null && RemoteEndPoint!.AddressFamily == AddressFamily.Unspecified &&
                                           nextIPv6AddressIndex >= 0 && nextUPv4AddressIndex >= 0;

                    if (parallelConnect)
                    {
                        nextAddressIndex = GetNextAddressIndex(addresses, AddressFamily.InterNetwork, -1);
                        nextIPv6AddressIndex = GetNextAddressIndex(addresses, AddressFamily.InterNetworkV6, -1);
                        internalArgs.SecondarySaea = new MultiConnectSocketAsyncEventArgs();
                    }
                    internalArgs.SocketError = SocketError.Success;
                    while (true)
                    {
                        if (!parallelConnect)
                        {
                            // We simply try addresses in sequence until we either try them all or operation is cancelled.
                            if (nextAddressIndex >= addresses.Length)
                            {
                                break;
                            }
                            address = addresses[nextAddressIndex];
                            nextAddressIndex++;
                        }

Review comment (refactor):
I wonder, if we should extract ip address index state management logic into different class and manage iterations over there? That can be done as separate PR tho.

Code after:
                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))
                    {
                        Socket? attemptSocket = null;
                        if (_currentSocket != null)
                        {
                            // If this SocketAsyncEventArgs was configured with a socket, then use it.
                            // If that instance doesn't support this address, move on to the next.
                            if (!_currentSocket.CanTryAddressFamily(address.AddressFamily))
                            {
                                continue;
                            }

                            attemptSocket = _currentSocket;
                        }
                        else
                        {
                            // If this SocketAsyncEventArgs doesn't have a socket, then we need to create a temporary one, which we do
                            // based on this address' address family (and then reuse for subsequent addresses for the same family).
                            if (address.AddressFamily == AddressFamily.InterNetworkV6)
                            {
                                attemptSocket = tempSocketIPv6 ??= (Socket.OSSupportsIPv6 ? new Socket(AddressFamily.InterNetworkV6, socketType, protocolType) : null);
                                if (attemptSocket is not null && address.IsIPv4MappedToIPv6)
                                {