Home > database >  Even while working with ConcurrentDictionary, the constructor gets called again
Even while working with ConcurrentDictionary, the constructor gets called again

Time:01-07

This is a follow-up of this question.

I am now working with ConcurrentDictionary, but while browsing through it, I am still launching the constructor of my Conn object, which is what I'm trying to avoid.

Source code:

public static ConcurrentDictionary<string, Conn> GetAllToDictionary(DbContext context)
{
    var result = new ConcurrentDictionary<string, Conn>();
    foreach (var conn in context.Set<Conn>().ToList())
        result.TryAdd(conn.Name, conn);
    return result;
}

Apparently, in the context.Set<Conn>().ToList(), the constructor of Conn gets called.

How can I avoid that? I just want to get the already existing Conn without re-creating one.

Edit: Conn constructor

My Conn constructor looks as follows:

public Conn(string name, IPAddress address, int port)
{
    Name = name;
    Address = address;
    Port = port;
    TcpConnection = new TcpConnection(Address, Port, 8192);
    Status = ConnectionStatus.NotConnected;
}

CodePudding user response:

What you want to do is get the address and port info from the database and then use it to build the connections.

Get rid of the constructor inside Conn and then change GetAllToDictionary to this:

public static ConcurrentDictionary<string, TcpConnection> GetAllToDictionary(DbContext context)
{
    var result = new ConcurrentDictionary<string, TcpConnection>();
    foreach (var conn in context.Set<Conn>().ToList())
        result.TryAdd(conn.Name, new TcpConnection(conn.Address, conn.Port, 8192););
    return result;
}

If the constructor inside Conn is referenced elsewhere and you cannot completely remove it, then just remove the line where you create the TcpConnection.

  • Related