Reputation: 6898
lock (_connectionLock) {
if (conn == null) {
conn = GetOpenConnection(connectionString);
}
try {
PerformDbAction(conn);
} finally {
conn.Dispose();
}
}
I have run into a problem where multithreading can cause issues with null connections as they can be opened and closed by several threads running at once. I tried to solve the issue by locking the process (above, code simplified for clarity) but have found that this seriously slows down the performance.
I tried to get around this problem by using two separate locks for the creation/disposal of database connections and to perform database action outside of locking:
lock (_connectionLock) {
if (conn == null) {
conn = GetOpenConnection(connectionString);
}
}
try {
PerformDbAction(conn);
} finally {
lock(_connectionLock)
conn.Dispose();
}
}
Only I realized that the above doesn't work as another thread may try to perform a database action with a connection that has already been disposed by another thread.
Could anyone suggest an alternative or solution where I can safely lock access to the database connection strings without slowing everything down so much?
EDIT: Sorry for not including this previously, but the reason I am not just creating new connections and disposing of them immediately is that I am trying to avoid unwanted MSDTC escalation. In using GetOpenConnection I am reusing an existing connection as this is one of the things that triggers MSDTC escalation.
I have managed to avoid the escalation with the top code example, but it performs way too slow.
Upvotes: 1
Views: 344
Reputation: 1500445
Simply don't have one shared connection variable. Instead, each time you need to do something, open a connection, use it, and close it as soon as you can. You don't need to use any locks in your code, and the connection pool will manage the real network connections to the database.
At the moment, you've essentially built a primitive connection pool containing exactly one connection, which means you've got no concurrency at all in the database (well, not per process).
Upvotes: 10