如何在Azure Service Bus Queue客户端中使用CancellationToken?

Mat*_*int 6 c# azure async-await azureservicebus cancellation-token

在Azure Service Bus队列客户端中,我使用该ReceiveBatchAsync方法等待指定的时间异步接收一批消息.

var messages = await queueClient.ReceiveBatchAsync(10, TimeSpan.FromSeconds(30));
Run Code Online (Sandbox Code Playgroud)

我想彻底关闭我的应用程序,所以我正在实现CancellationToken所有长期运行的异步进程,但似乎没有可以ReceiveBatchAsync取消的重载.

换句话说,我想这样做,但我不能:

var messages = await queueClient.ReceiveBatchAsync(10, TimeSpan.FromSeconds(30),
                                                       cancellationToken);
Run Code Online (Sandbox Code Playgroud)

将这样CancellationToken的任务应用于不直接提供的任务的最佳方法是什么?我不想在关机期间等待整整30秒.

nos*_*tio 3

你可能可以QueueClient.Abort这样使用:

using (cancellationToken.Register(() => queueClient.Abort())
{
    var messages = await queueClient.ReceiveBatchAsync(
        10, TimeSpan.FromSeconds(30));
    return messages; // or process it 
}
Run Code Online (Sandbox Code Playgroud)

  • 我今天遇到了这个。这个解决方案对我有用,至少通过 Linqpad 进行快速检查。取消令牌时抛出OperationCanceledException。 (2认同)