Skip to content

Instantly share code, notes, and snippets.

@rcollette
Created August 16, 2013 19:19
Show Gist options
  • Save rcollette/6252733 to your computer and use it in GitHub Desktop.
Save rcollette/6252733 to your computer and use it in GitHub Desktop.
Performance test code comparing IDataReader disposal prior to all records being read, using IDbCommand.Cancel() and without using Cancel()
namespace DataReaderDisposeCancelTest
{
using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
internal class Program
{
private const int iterations = 50;
private static void CancelTest(IDbCommand cmd)
{
for (int i = 0; i < iterations; i++)
{
using (IDataReader reader = cmd.ExecuteReader())
{
reader.Read();
string x = reader[0] as string;
cmd.Cancel();
}
}
}
private static void Main(string[] args)
{
var cs = ConfigurationManager.ConnectionStrings["ConnectionString"];
DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName);
using (var conn = factory.CreateConnection())
{
conn.ConnectionString = cs.ConnectionString;
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = "select * from dbo.someTable";
CancelTest(cmd);
NoCancelTest(cmd);
}
}
private static void NoCancelTest(IDbCommand cmd)
{
for (int i = 0; i < iterations; i++)
{
using (IDataReader reader = cmd.ExecuteReader())
{
reader.Read();
string x = reader[0] as string;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment