Cancel long-running Dapper Query

c# dapper

Question

We have a winforms application which uses Dapper for database reads.

In one form we have a (possible) long running query on a background thread.

The users want to be able to cancel the query, so i need access to the DbCommand Dapper creates and call Cancel on it, if it is running, from another thread.

What would be the best way of exposing this DbCommand from Dapper?

Popular Answer

It's hammer time. Break stuff.

using (var reader = connection.ExecuteReader(query)) {

.... now to cancel

var wrappedReaderType = typeof (Dapper.CommandDefinition)
                        .Assembly.GetType("Dapper.WrappedReader");
var field = wrappedReaderType
            .GetField("cmd", BindingFlags.NonPublic | BindingFlags.Instance);
if (field != null)
{
    var command = field.GetValue(reader) as IDbCommand;
    if (command != null)
    {
        command.Cancel();
    }
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why