问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/39166619/will-this-cancel-an-executereaderasync