问题描述
请考虑此代码示例:
const int timeoutInSeconds = 60; // 1 minute
static readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
public static void Main()
{
try
{
tokenSource.CancelAfter(timeoutInSeconds * 1000);
Task.WaitAll(ReadLargeFile(),TimeStat());
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine(e.Message);
}
}
finally
{
tokenSource.dispose();
}
}
static async Task ReadLargeFile()
{
using (var con = new sqlConnection($"some connection string"))
{
await con.OpenAsync(tokenSource.Token).ConfigureAwait(false);
using (var command = new sqlCommand("SELECT * FROM dbo.TableWithFatRows where Id = 1",con))
{
command.CommandTimeout = timeoutInSeconds;
sqlDataReader reader = await command.ExecuteReaderAsync(CommandBehavior.Default,tokenSource.Token).ConfigureAwait(false);
while (await reader.ReadAsync(tokenSource.Token).ConfigureAwait(false)) // we expect cancellation here
{
Console.WriteLine($"Finished Read iteration. Checking cancellation ");
tokenSource.Token.ThrowIfCancellationRequested(); // but actually we got it here
// some work
}
}
}
}
static async Task TimeStat(int secondsDelay = 10)
{
try
{
while (!tokenSource.IsCancellationRequested)
{
Console.WriteLine($"#TotalSeconds: {stopwatch.Elapsed.TotalSeconds}");
await Task.Delay(new TimeSpan(0,secondsDelay),tokenSource.Token).ConfigureAwait(false); ;
}
}
catch (TaskCanceledException)
{
Console.WriteLine("Cancellation has been requested. Finishing TimeStat task.");
}
}
问题 - 我们必须从表中查询非常大的行。例如。每个 15Mb。 而且通常读取一行需要10分钟以上。
问题是 - 如何强制 sqlDataReader
中止/关闭数据检索过程?
目前在上面的代码中 - sqlDataReader
只是忽略请求的取消,可能是设计使然。
因此,执行会卡在数据读取过程 (await reader.ReadAsync(tokenSource.Token)
) 上,直到大行完全下载并违反所有连接/命令/取消令牌超时。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)