@@ -165,21 +165,10 @@ private void ConfigureConnectedSocket(Socket socket)
165165
166166 private void Connect ( Socket socket , EndPoint endPoint , CancellationToken cancellationToken )
167167 {
168- var cancelledOrTimedOut = false ;
168+ var isSocketDisposed = false ;
169169 using var timeoutCancellationTokenSource = new CancellationTokenSource ( _settings . ConnectTimeout ) ;
170170 using var combinedCancellationTokenSource = CancellationTokenSource . CreateLinkedTokenSource ( cancellationToken , timeoutCancellationTokenSource . Token ) ;
171- using var cancellationSubscription = combinedCancellationTokenSource . Token . Register ( ( ) =>
172- {
173- try
174- {
175- cancelledOrTimedOut = true ;
176- socket . Dispose ( ) ;
177- }
178- catch
179- {
180- // Ignore any exception here, as we should avoid throwing in callback.
181- }
182- } ) ;
171+ using var cancellationSubscription = combinedCancellationTokenSource . Token . Register ( DisposeSocket ) ;
183172
184173 try
185174 {
@@ -199,16 +188,9 @@ private void Connect(Socket socket, EndPoint endPoint, CancellationToken cancell
199188 }
200189 catch ( Exception )
201190 {
202- if ( ! cancelledOrTimedOut )
191+ if ( ! isSocketDisposed )
203192 {
204- try
205- {
206- socket . Dispose ( ) ;
207- }
208- catch
209- {
210- // Ignore any exceptions. Connection was failed, we do not need the socket anyway.
211- }
193+ DisposeSocket ( ) ;
212194 }
213195
214196 cancellationToken . ThrowIfCancellationRequested ( ) ;
@@ -219,6 +201,19 @@ private void Connect(Socket socket, EndPoint endPoint, CancellationToken cancell
219201
220202 throw ;
221203 }
204+
205+ void DisposeSocket ( )
206+ {
207+ isSocketDisposed = true ;
208+ try
209+ {
210+ socket . Dispose ( ) ;
211+ }
212+ catch
213+ {
214+ // Ignore any exceptions.
215+ }
216+ }
222217 }
223218
224219 private async Task ConnectAsync ( Socket socket , EndPoint endPoint , CancellationToken cancellationToken )
0 commit comments