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

Code before:
                                    {
                                        // We need a DualMode socket to connect to an IPv6-mapped IPv4 address.
                                        attemptSocket.DualMode = true;
                                    }
                                }
                                else if (address.AddressFamily == AddressFamily.InterNetwork)
                                {
                                    attemptSocket = tempSocketIPv4 ??= (Socket.OSSupportsIPv4 ? new Socket(AddressFamily.InterNetwork, socketType, protocolType) : null);
                                }
                            }

                            if (address2 != null)
                            {
                                Debug.Assert(internalArgs.SecondarySaea != null);

                                // if we have two addressess to connect to: IPv4 is in address and IPv6 in address2
                                Debug.Assert(address2.AddressFamily == AddressFamily.InterNetworkV6);
                                attemptSocket2 = tempSocketIPv6 ??= (Socket.OSSupportsIPv6 ? new Socket(AddressFamily.InterNetworkV6, socketType, protocolType) : null);
                                if (attemptSocket2 is not null && address2.IsIPv4MappedToIPv6)
                                {
                                    // We need a DualMode socket to connect to an IPv6-mapped IPv4 address.
                                    attemptSocket2.DualMode = true;
                                }
                                internalArgs.SecondarySaea._currentSocket = attemptSocket2;

                                internalArgs.SecondarySaea.Completed += (s, e) =>
                                {
                                    Socket? socket = s as Socket;
                                    MultiConnectSocketAsyncEventArgs? me = e.UserToken as MultiConnectSocketAsyncEventArgs;
                                    if (me == null)
                                    {
                                        // primary connection is already done.
                                        socket?.Dispose();
                                    }
                                    else
                                    {
                                        me.OnCompleted(e);
                                    }

                                };
                                if (internalArgs.SecondarySaea.RemoteEndPoint is IPEndPoint existing2)
                                {
                                    existing2.Address = address2;
                                    Debug.Assert(existing2.Port == port);
                                }
                                else
                                {
                                    internalArgs.SecondarySaea.RemoteEndPoint = new IPEndPoint(address2, port);
                                    internalArgs.SecondarySaea.SocketError = SocketError.IOPending;
                                    internalArgs.SecondarySaea.UserToken = internalArgs;
                                }

Review comment (refactor):
Is this really needed given that we are doing `Task.WhenAny` later? Isn't the current logic choosing the winner and cleaning up stuff after the `await` anyways? If not can we simplify it to do so? It's weird to have such an event subscription in an `async` method.

Code after:
                    if (tempSocketIPv4 != null && !tempSocketIPv4.Connected)
                    {
                        tempSocketIPv4.Dispose();
                    }
                    if (tempSocketIPv6 != null && !tempSocketIPv6.Connected)
                    {
                        tempSocketIPv6.Dispose();
                    }

                    if (parallelState != null)
                    {
                        // If we do parallel connect use SetResults from there to arbiter competing results.
                        if (caughtException != null)
                        {
                            parallelState.SetResults(null, internalArgs.SocketError, 0, SocketFlags.None, caughtException);
                        }
                        else
                        {
                            parallelState.SetResults(internalArgs.ConnectSocket, internalArgs.SocketError, internalArgs.BytesTransferred, internalArgs.SocketFlags, null);
                        }
                        internalArgs.Dispose();
                    }
                    else
                    {
                        if (_currentSocket != null)
                        {
                            // If the caller-provided socket was a temporary and isn't connected now, or if it failed with an abortive exception,
                            // dispose of the socket.
                            if ((!_userSocket && !_currentSocket.Connected) ||
                                caughtException is OperationCanceledException ||
                                (caughtException is SocketException se && se.SocketErrorCode == SocketError.OperationAborted))
                            {
                                _currentSocket.Dispose();
                            }
                        }

                        // Store the results.
                        if (caughtException != null)
                        {
                            SetResults(caughtException, 0, SocketFlags.None);
                            _currentSocket?.UpdateStatusAfterSocketError(_socketError);
                        }
                        else
                        {
                            SetResults(SocketError.Success, internalArgs.BytesTransferred, internalArgs.SocketFlags);
                            _connectSocket = _currentSocket = internalArgs.ConnectSocket!;
                        }

                        // Complete the operation.
                        if (SocketsTelemetry.Log.IsEnabled()) LogBytesTransferEvents(_connectSocket?.SocketType, SocketAsyncOperation.Connect, internalArgs.BytesTransferred);