Is this NpgsqlConnection factory thread safe?

Viewed 3868

Is this code thread safe?

public static NpgsqlConnection getConnection()
{          
    NpgsqlConnectionStringBuilder csb = new NpgsqlConnectionStringBuilder();
    csb.Host = ConfigurationManager.AppSettings["server"];
    csb.Password = ConfigurationManager.AppSettings["password"];
    csb.Pooling = true;
    csb.UserName = ConfigurationManager.AppSettings["username"];
    csb.Port = Convert.ToInt32( ConfigurationManager.AppSettings["port"]);
    csb.Enlist = true;
    //csb.Database = ConfigurationManager.AppSettings["databaseName"];

    return new NpgsqlConnection(csb.ConnectionString);
}

I use this connection everywhere, but sometimes I get a TimeoutException.

A timeout has occured. If you were establishing a connection, increase Timeout value in ConnectionString. If you were executing a command, increase the CommandTimeout value in ConnectionString or in your NpgsqlCommand object.

Any ideas?

2 Answers

No, this is not thread safe, because csb is not local and likely not thread safe. Use a local csb. Check if ConfigurationManager is thread safe.

Instantiating the connection itself is thread safe, as other threads cannot "see" the instance. Your connection problems probably stem from somewhere else. You may want to try what was given as a hint in the error message.

Related