File tree 1 file changed +19
-1
lines changed 1 file changed +19
-1
lines changed Original file line number Diff line number Diff line change @@ -1788,22 +1788,40 @@ internal static string ToHex(byte[] bytes)
1788
1788
/// when the value of <see cref="Socket.Available"/> is obtained. To workaround this issue
1789
1789
/// we synchronize reads from the <see cref="Socket"/>.
1790
1790
/// </para>
1791
+ /// <para>
1792
+ /// We assume the socket is still connected if the read lock cannot be acquired immediately.
1793
+ /// In this case, we just return <see langword="true"/> without actually waiting to acquire
1794
+ /// the lock. We don't want to wait for the read lock if another thread already has it because
1795
+ /// there are cases where the other thread holding the lock can be waiting indefinitely for
1796
+ /// a socket read operation to complete.
1797
+ /// </para>
1791
1798
/// </remarks>
1792
1799
private bool IsSocketConnected ( )
1793
1800
{
1801
+ #pragma warning disable S2222 // Locks should be released on all paths
1794
1802
lock ( _socketDisposeLock )
1795
1803
{
1796
1804
if ( ! _socket . IsConnected ( ) )
1797
1805
{
1798
1806
return false ;
1799
1807
}
1800
1808
1801
- lock ( _socketReadLock )
1809
+ if ( ! Monitor . TryEnter ( _socketReadLock ) )
1810
+ {
1811
+ return true ;
1812
+ }
1813
+
1814
+ try
1802
1815
{
1803
1816
var connectionClosedOrDataAvailable = _socket . Poll ( 0 , SelectMode . SelectRead ) ;
1804
1817
return ! ( connectionClosedOrDataAvailable && _socket . Available == 0 ) ;
1805
1818
}
1819
+ finally
1820
+ {
1821
+ Monitor . Exit ( _socketReadLock ) ;
1822
+ }
1806
1823
}
1824
+ #pragma warning restore S2222 // Locks should be released on all paths
1807
1825
}
1808
1826
1809
1827
/// <summary>
You can’t perform that action at this time.
0 commit comments