Will this cancel an ExecuteReaderAsync

筅森魡賤 提交于 2020-01-07 08:15:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!