Fanda
Fanda

Reputation: 3786

.NET how to monitor db connection interruption?

Is there any way how to monitor database connection for interruptions? I have one connection shared across applications and some objects should react on connection interruption.

Ideally it should be an event. The only thing I found is a connection exception, but it is raised locally (where I am listening for exceptions).

I have idea to inherit from DbConnection and listen for exception in this object (overloading its methods), raising signal on connection error exception (by related code). But maybe there is simplest way.

Thank you of ideas.

Upvotes: 1

Views: 638

Answers (1)

Marcel N.
Marcel N.

Reputation: 13986

Sharing a single connection is never good and it IS a bad practice. The main reason is actually your problem. I suggest you change your design a bit (not a big deal) and rely on the ADO.NET connection pooling. It's a must have in case you don't want to run into all kinds of bottlenecks, especially in multithreading situations.

It means that all your connections are transient and you create one only when you need to go to the database.

You can read more about it here, where you can also find samples on how to use it. The main thing to know about it is that it uses the Disposable pattern.

//Notice the **using ** block
using(SqlConnection conn = new SqlConnection(connString)) 
{
  conn.Open();
  //do something with the connection.
  //as soon as the using block ends, the managed connection is disposed and released in the pool
}

Upvotes: 7

Related Questions