Created
December 14, 2013 11:20
-
-
Save FransBouma/7958092 to your computer and use it in GitHub Desktop.
Optimization for closing a SqlDataReader as it otherwise can be rather slow with pulling statistics and non-read rows before it actually closes the reader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Cleans up the data reader (closes it if necessary and disposes it) | |
/// </summary> | |
/// <param name="reader">The reader.</param> | |
/// <param name="queryExecuted">The query executed.</param> | |
/// <param name="disposeReader">if set to <c>true</c> [dispose reader].</param> | |
internal static void CleanupDataReader(IDataReader reader, IQuery queryExecuted, bool disposeReader) | |
{ | |
if(reader != null) | |
{ | |
if(!reader.IsClosed) | |
{ | |
System.Data.SqlClient.SqlDataReader sqlServerReader = reader as System.Data.SqlClient.SqlDataReader; | |
// only do optimization if there are rows and the command isn't in a transaction, as some reports suggest that cancelling a command in a transaction | |
// can cause problems. | |
if((sqlServerReader != null) && (queryExecuted!=null) && (queryExecuted.Command!=null) && (queryExecuted.Command.Transaction==null) && | |
sqlServerReader.Read()) | |
{ | |
// optimization: call cancel first, this will greatly reduce the time it takes to Close the datareader as we're not interested in | |
// any statistics gathered by Close anyway. Required for SqlServer, other providers don't have a slow Close() method. | |
queryExecuted.Command.Cancel(); | |
} | |
reader.Close(); | |
} | |
if(disposeReader) | |
{ | |
reader.Dispose(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment