Hi there!
Problem:
I am refactoring all my database code because I noticed every few days
sqlservr.exe would show as Mem Usage of 500,000k in the task manager and
crash our server.
Solution:
I wanted to be able to use the .Dispose() command and found the "using"
directive would do the trick. I have refactored a few try/catch/finally
blocks but found there is no way to CATCH the error and that is where I
usually write to an error log on the server describing the error.
For example here is some code:
using (SqlConnection sqlConn = new
SqlConnection(Constants.DATABASE_CONNECTION_STRING ))
{
using (SqlCommand sqlCmd = new SqlCommand(strSQL, sqlConn))
{
sqlConn.Open();
using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
{
if (sqlReader.HasRows)
{
while (sqlReader.Read())
{
// Some database code here
}
}
}
}
}
See, there is no try/catch block AT ALL!
Question:
If I code things this way, will I always miss out on catching errors? In
any program, the error could happen anywhere. A "normal" way would just be
to use the try/catch at the sqlReader.Read() part, but what if the error
happens at sqlConn.Open(), then we'd miss the error completely and the
program would crash right?
So, as far as .Dispose() goes this seems the way to go for resource/garbage
handling, but if you can't trap errors why would someone want to use this?
Again, If we received an error on sqlConn.Open() wouldn't the program crash?
There is see no catching the program crash unless we got rid of the "using"
directive right?
Please advise. Thanks in advance.
R Reyes