Skip to content

Commit

Permalink
Gh58 fix update (#339)
Browse files Browse the repository at this point in the history
* Use CancellationTokenResource only for non-infinite timeout

* Release CancellationTokenResource when done
  • Loading branch information
karinazhou authored Dec 3, 2019
1 parent 40f3bf8 commit e17f170
Showing 1 changed file with 29 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -198,17 +198,8 @@ private static Socket Connect(string serverName, int port, TimeSpan timeout, boo
ipAddresses = new IPAddress[] { serverIPv4, serverIPv6 };
Socket[] sockets = new Socket[2];

CancellationTokenSource cts = new CancellationTokenSource();
CancellationTokenSource cts = null;

if (isInfiniteTimeout)
{
cts.CancelAfter(-1);
}
else
{
cts.CancelAfter(timeout);
}

void Cancel()
{
for (int i = 0; i < sockets.Length; ++i)
Expand All @@ -224,33 +215,45 @@ void Cancel()
catch { }
}
}
cts.Token.Register(Cancel);

if (!isInfiniteTimeout)
{
cts = new CancellationTokenSource(timeout);
cts.Token.Register(Cancel);
}

Socket availableSocket = null;
for (int i = 0; i < sockets.Length; ++i)
try
{
try
for (int i = 0; i < sockets.Length; ++i)
{
if (ipAddresses[i] != null)
try
{
sockets[i] = new Socket(ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sockets[i].Connect(ipAddresses[i], port);
if (sockets[i] != null) // sockets[i] can be null if cancel callback is executed during connect()
if (ipAddresses[i] != null)
{
if (sockets[i].Connected)
{
availableSocket = sockets[i];
break;
}
else
sockets[i] = new Socket(ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sockets[i].Connect(ipAddresses[i], port);
if (sockets[i] != null) // sockets[i] can be null if cancel callback is executed during connect()
{
sockets[i].Dispose();
sockets[i] = null;
if (sockets[i].Connected)
{
availableSocket = sockets[i];
break;
}
else
{
sockets[i].Dispose();
sockets[i] = null;
}
}
}
}
catch { }
}
catch { }
}
finally
{
cts?.Dispose();
}

return availableSocket;
Expand Down

0 comments on commit e17f170

Please sign in to comment.