Search code examples
c#executereader

Will this cancel an ExecuteReaderAsync


If I make a CancellationTokenSource and pass it down to a place where I perform a query like this:

await command.Connection.OpenAsync();
dataReader = await command.ExecuteReaderAsync(_cancellationToken);

If immediately below this I add the following:

_cancellationToken.ThrowIfCancellationRequested();
resultTable.Load(dataReader);

If on a different thread _cancellationTokenSource.Cancel() is called, will the query be cancelled appropriately?


Solution

  • Was able to find a decent solution to the problem. Given the cancellation token and a SQLCommand, wrapping the loading to a data table as follows successfully cancels the db query:

    using (CancellationTokenRegistration ctr = cancellationToken.Register(() => cmd.Cancel()))
    {
         using (var reader = cmd.ExecuteReaderAsync(cancellationToken))
         {
             dataTable.Load(reader.Result);
         }
    }
    

    So when the cancellationToken is cancelled in a different thread, the cmd.Cancel is called automatically. This will throw a SqlException that I had to handle and perform my cleanup.