TheCatWhisperer
TheCatWhisperer

Reputation: 981

StackExchange.ConnectionMultiplexer.GetServer not working

        using (ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("redisIP:6379,allowAdmin=true"))
        {

            Model.SessionInstances = connection.GetEndPoints()
                .Select(endpoint =>
                {                      
                    var status = new Status();
                    var server = connection.GetServer(endpoint); // Exception thrown here!
                    status.IsOnline = server.IsConnected;
                    return status;
                 });
         }

The above code is running in the code behind of an ASP.NET ASPX page. I have very similar code running in a command line program that works fine, so I am not sure what I am doing wrong here. The only difference is that code is using a foreach loop instead of lambdas.

Every time I run this code, I get an exception The specified endpoint is not defined

I find this to be strange as I am getting the endpoints from the very same connection. The endpoints being returned are correct.

What am I doing wrong here?


I do realize that I should not be opening a new connection every page load, but this is an infrequently accessed admin page for me only; so I am not worried about the performance overhead. Also, my saved connection is hidden inside a CacheClass that abstracts away the particular provider.

Upvotes: 3

Views: 7758

Answers (1)

kmatyaszek
kmatyaszek

Reputation: 19296

You are experiencing this error because the enumerable returned by your lambda expression is being lazy evaluated. By the time your lambda expression runs, your connection has already been closed by the using statement.

Inside using statement you should execute your lambda expression e.g. by adding .ToList() on the end:

using (ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("redisIP:6379,allowAdmin=true"))
{
      Model.SessionInstances = connection.GetEndPoints()
        .Select(endpoint =>
        {
            var status = new Status();
            var server = connection.GetServer(endpoint);
            status.IsOnline = server.IsConnected;
            return status;
        }).ToList();
 }

Upvotes: 5

Related Questions