Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I see few problems in your code.</p> <ol> <li>Try to use the Reader in a using statement it closes and disposes when finishing it.</li> <li><p>You are closing 2 times the connection (when using </p> <p><code>if (cn != null &amp;&amp; cn.State !=ConnectionState.Closed) cn.Close();</code> and in the <code>using (SqlConnection cn = Connections.GetSqlConnection())</code> -- this one do it for you at the end of the statement</p></li> <li><p>In your code you are not checking if the <a href="http://msdn.microsoft.com/es-es/library/system.data.sqlclient.sqldatareader.hasrows.aspx" rel="nofollow"> DataReader.HasRows</a> So if your Sproc doesn't return a value it will throw an exception in the <code>if (dr.Read())</code> so that could be the reason that's why you are getting sometimes the time out exception</p></li> <li>If you only want to retrieve the value of the first column of the first row you should take a look to <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx" rel="nofollow">ExecuteScalar</a> </li> </ol> <p>Finally I would rewrite your code like this (using DataReader)</p> <pre><code>public double GetMyData() { double returnValue; // Used in logging to see if code was reached &amp; how long it took. System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch(); using (SqlConnection cn = Connections.GetSqlConnection()) { cn.Open(); using (SqlCommand cmd = getSQLCommmand("SomeProcName")) { Log.Log.WriteTrace(string.Format("Execute {0} ","SomeProcName"),0); s.Start(); using(SqlDataReader dr = cmd.ExecuteReader()) { s.Stop(); Log.Log.WriteTrace("Timer", "ExecuteReader done " + s.ElapsedMilliseconds + "ms ", 0); s.Start(); if (dr != null) { if(dr.HasRows) { if (dr.Read()) { returnValue = Conversion.DBNullToDouble( dr[0]); } } s.Stop(); Log.Log.WriteTrace("Timer", "dr.read done (result:" + returnValue + ")" + s.ElapsedMilliseconds + "ms ", 0); // I get Here } } } } return (returnValue); } </code></pre> <p>Or (with ExecuteScalar)</p> <pre><code>public double GetMyData() { double returnValue; // Used in logging to see if code was reached &amp; how long it took. System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch(); using (SqlConnection cn = Connections.GetSqlConnection()) { cn.Open(); using (SqlCommand cmd = getSQLCommmand("SomeProcName")) { Log.Log.WriteTrace(string.Format("Execute {0} ","SomeProcName"),0); s.Start(); try { returnValue = Conversion.DBNullToDouble(cmd.ExecuteScalar()); s.Stop(); } catch(Exception ex) { Log.Log.PersistException(ex); } } } return (returnValue); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload