Exemplo n.º 1
0
        private void EnsureConnection()
        {
            var tcs = new TaskCompletionSource <object>();

            if (Interlocked.CompareExchange(ref _connectingTask, tcs.Task, null) != null)
            {
                // Give all clients the same task for reconnecting
                return;
            }

            try
            {
                if (_connection == null)
                {
                    _connection         = new RedisConnection(_server, _port, password: _password);
                    _connection.Closed += (sender, e) =>
                    {
                        // Reconnect on close
                        Disconnect();
                        EnsureConnection();
                    };
                }

                // Open the connection
                _connection.Open().ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        tcs.SetException(task.Exception);
                    }
                    else if (task.IsCanceled)
                    {
                        tcs.SetCanceled();
                    }
                    else
                    {
                        try
                        {
                            // Initialize the subscriber channel
                            var channel = _connection.GetOpenSubscriberChannel();

                            // Subscribe to the bus event
                            channel.Subscribe(_eventKey, OnMessage);

                            // Mark the connection as ready
                            _connectionReady = true;

                            // Mark the task as completed
                            tcs.SetResult(null);
                        }
                        catch (Exception ex)
                        {
                            tcs.SetException(ex);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }
        }
Exemplo n.º 2
0
 private void Disconnect()
 {
     Interlocked.Exchange(ref _connectingTask, null);
     _connectionReady = false;
     _connection      = null;
 }