如何将 cancellationToken "as necessary" 与 Azure 服务总线一起使用?

How to use cancellationToken "as necessary" with Azure Service Bus?

Azure Service Bus documentation 中有一条评论说:

// Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.

// If queueClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.

// to avoid unnecessary exceptions.

我一直在尝试查找有关如何使用令牌 "as necessary" 的更多信息,但对我来说并不明显。我尝试阅读有关 Task Cancellation 的部分,但结果 none 更明智。

令牌有一些属性,CanBeCancelledIsCancellationRequested 看起来很有趣。

if (!token.IsCancellationRequested)
{
    await queueClient.CompleteAsync(message.SystemProperties.LockToken);
}

if (token.CanBeCanceled)
{
    await queueClient.CompleteAsync(message.SystemProperties.LockToken);
}

在查看锁定模式下接收消息时,如何正确使用令牌 "as necessary"?

IsCancellationRequested 属性 是您正在寻找的那个,您分享的 if 语句就是您应该如何使用它。

此外,您也可以在开始任何长 运行 进程之前进行相同的检查,因为我想无论如何都会重新处理消息。