为什么 OperationCancelledException 传递的 CancellationToken 与来自 CTSource 的 CancellationToken 不同?

use*_*063 4 c# ado.net async-await

为什么异常中存储的 CancellationToken 与 CancellationTokenSource 提供的令牌不同?

[Test]
public static async Task SqlCommand_should_recognise_which_CT_triggered_its_cancellation()
{

    var timeout = TimeSpan.FromSeconds(1);
    var cts = new CancellationTokenSource(timeout);

    try
    {
        var connection = new SqlConnection(_config.ConnectionString);
        await connection.OpenAsync(cts.Token);
        var sqlQuery = new SqlCommand("select 1", connection);

        await Task.Delay(timeout + TimeSpan.FromSeconds(1));
        await sqlQuery.ExecuteScalarAsync(cts.Token);
    }
    catch (OperationCanceledException cancelledEx)
    {
        //Shouldn't they be the same?
        Assert.AreEqual(cancelledEx.CancellationToken, cts.Token);
        // The below fails as well
        // Assert.IsTrue(cancelledEx.CancellationToken == cts.Token);


    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ary 5

为什么异常中存储的 CancellationToken 与 CancellationTokenSource 提供的令牌不同?

这是一个实施细节。我没有查看源代码,但我怀疑正在发生的事情是CancellationToken提供给正在ExecuteScalarAsync与一些内部结合CancellationToken,这意味着“我们失去了连接”或类似的东西。这些链接的CancellationTokens不等于它们的 source CancellationTokens。

CancellationToken这是一般 s的使用问题。对于链接令牌,并不总是能够确定是哪个取消令牌导致了取消。因此,我建议您通过以下方式检查您自己的取消令牌副本catch (OperationCanceledException ex) when (cts.IsCancellationRequested)

static async Task Main(string[] args)
{
  var timeout = TimeSpan.FromSeconds(1);
  var cts = new CancellationTokenSource(timeout);

  try
  {
    await IndirectDelay(10, cts.Token);

    await Task.Delay(timeout + TimeSpan.FromSeconds(1));
    await IndirectDelay(10, cts.Token);
  }
  catch (OperationCanceledException ex) when (cts.IsCancellationRequested)
  {
    Console.WriteLine(ex.CancellationToken == cts.Token); // false
    Console.WriteLine("Our token is canceled.");
  }
  catch (OperationCanceledException)
  {
    Console.WriteLine("Canceled for some other reason.");
  }
  catch (Exception)
  {
    Console.WriteLine("General error.");
  }
}

private static async Task IndirectDelay(int timeout, CancellationToken token)
{
  using (var internalCts = new CancellationTokenSource())
  using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token, internalCts.Token))
    await Task.Delay(timeout, cts.Token);
}
Run Code Online (Sandbox Code Playgroud)

存在竞争条件的可能性,您的代码会认为取消是由于超时而发生的,但实际上这是因为连接断开(或发生任何内部逻辑),但在大多数情况下这并不重要。