public Task <INetChannel> Connect(IPEndPoint endPoint, CancellationToken cancellationToken) { //check if we are already connected to this endpoint foreach (var pair in ChannelsById) { if (endPoint.Equals(pair.Value.TransportChannel.EndPoint)) { return(Task.FromResult((INetChannel)pair.Value)); } } return(_pendingConnections.AddOrUpdate(endPoint, (key) => { var val = new PendingConnection(key); _logger.ConnectingTo(this, endPoint); Net.Connect(endPoint); var expiration = Task.Delay(TimeSpan.FromSeconds(_config.ConnectTimeoutSec), val.Expiration.Token); expiration.ContinueWith(task => { if (!task.IsCanceled) { _logger.ConnectionHasTimedOut(this, endPoint); PendingConnection cont; if (_pendingConnections.TryRemove(key, out cont)) { cont.TCS.SetException(new ConnectionFailedException(key)); } } }, cancellationToken); return val; }, (key, val) => val ).TCS.Task); }