6

In the Azure Service Bus queue client, I use the ReceiveBatchAsync method to wait for a specified time to receive a batch of messages asynchronously.

var messages = await queueClient.ReceiveBatchAsync(10, TimeSpan.FromSeconds(30));

I'd like a clean shutdown of my application, so I'm implementing CancellationToken on all of my long-running async processes, but there doesn't appear to be an overload of ReceiveBatchAsync that is cancelable.

In other words, I'd like to do this, but I can't:

var messages = await queueClient.ReceiveBatchAsync(10, TimeSpan.FromSeconds(30),
                                                       cancellationToken);

What would be the best way to apply a CancellationToken to a task like this that doesn't offer it directly? I don't want to wait the entire 30 seconds during shutdown.

1 Answer 1

3

You probably could use QueueClient.Abort like this:

using (cancellationToken.Register(() => queueClient.Abort())
{
    var messages = await queueClient.ReceiveBatchAsync(
        10, TimeSpan.FromSeconds(30));
    return messages; // or process it 
}
4
  • Looks good on the surface. But do you know if it will actually interrupt the timeout? I'll have to try it and see. May 15, 2014 at 5:00
  • @MattJohnson, I don't know for sure as I haven't happened to use ReceiveBatchAsync yet.
    – noseratio
    May 15, 2014 at 5:01
  • If it doesn't, you can always combine your cancellationToken with a timeout CancellationToken via CancellationTokenSource instead of using a timeout in the call to QueueClient.ReceiveBytesAsync. May 15, 2014 at 6:36
  • 2
    I ran into this today. This solution worked for me, at least in a quick check via Linqpad. OperationCanceledException was thrown when the token was cancelled. Jun 28, 2017 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.